diff --git a/Common/UnitDefinitions/Molality.json b/Common/UnitDefinitions/Molality.json new file mode 100644 index 0000000000..d28ac2c9c5 --- /dev/null +++ b/Common/UnitDefinitions/Molality.json @@ -0,0 +1,44 @@ +{ + "Name": "Molality", + "BaseUnit": "MolePerKilogram", + "XmlDocSummary": "Molality is a measure of the amount of solute in a solution relative to a given mass of solvent.", + "XmlDocRemarks": "https://en.wikipedia.org/wiki/Molality", + "BaseDimensions": { + "N": 1, + "M": -1 + }, + "Units": [ + { + "SingularName": "MolePerKilogram", + "PluralName": "MolesPerKilogram", + "BaseUnits": { + "N": "Mole", + "M": "Kilogram" + }, + "FromUnitToBaseFunc": "{x}", + "FromBaseToUnitFunc": "{x}", + "Localization": [ + { + "Culture": "en-US", + "Abbreviations": [ "mol/kg" ] + } + ] + }, + { + "SingularName": "MolePerGram", + "PluralName": "MolesPerGram", + "BaseUnits": { + "N": "Mole", + "M": "Gram" + }, + "FromUnitToBaseFunc": "{x} / 1e-3", + "FromBaseToUnitFunc": "{x} * 1e-3", + "Localization": [ + { + "Culture": "en-US", + "Abbreviations": [ "mol/g" ] + } + ] + } + ] +} diff --git a/Common/UnitEnumValues.g.json b/Common/UnitEnumValues.g.json index 13e827c58c..bb6b5d565a 100644 --- a/Common/UnitEnumValues.g.json +++ b/Common/UnitEnumValues.g.json @@ -1790,5 +1790,9 @@ "Picogray": 11, "Rad": 17, "Teragray": 14 + }, + "Molality": { + "MolePerGram": 4, + "MolePerKilogram": 1 } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Molality/Molality.nfproj b/UnitsNet.NanoFramework/GeneratedCode/Molality/Molality.nfproj new file mode 100644 index 0000000000..0a503cfec7 --- /dev/null +++ b/UnitsNet.NanoFramework/GeneratedCode/Molality/Molality.nfproj @@ -0,0 +1,42 @@ + + + + $(MSBuildExtensionsPath)\nanoFramework\v1.0\ + + + + Debug + AnyCPU + {11A8DD76-328B-46DF-9F39-F559912D0360};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + {589b202c-e638-5c93-fefe-e1e3bab4a493} + Library + Properties + 512 + UnitsNet + UnitsNet.Molality + v1.0 + bin\$(Configuration)\$(AssemblyName).xml + + + + + + + + + + ..\packages\nanoFramework.CoreLibrary.1.15.5\lib\mscorlib.dll + True + True + + + + + + + + + + + + diff --git a/UnitsNet.NanoFramework/GeneratedCode/Molality/UnitsNet.NanoFramework.Molality.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Molality/UnitsNet.NanoFramework.Molality.nuspec new file mode 100644 index 0000000000..4cbc203ae2 --- /dev/null +++ b/UnitsNet.NanoFramework/GeneratedCode/Molality/UnitsNet.NanoFramework.Molality.nuspec @@ -0,0 +1,26 @@ + + + + UnitsNet.nanoFramework.Molality + 5.39.0 + Units.NET Molality - nanoFramework + Andreas Gullberg Larsen,nanoframework + UnitsNet + MIT + https://github.com/angularsen/UnitsNet + false + Adds Molality units for Units.NET on .NET nanoFramework. For .NET or .NET Core, use UnitsNet instead. + https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png + + + Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). + en-US + nanoframework molality unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable + + + + + + + + diff --git a/UnitsNet.NanoFramework/GeneratedCode/Molality/packages.config b/UnitsNet.NanoFramework/GeneratedCode/Molality/packages.config new file mode 100644 index 0000000000..313a8dccdf --- /dev/null +++ b/UnitsNet.NanoFramework/GeneratedCode/Molality/packages.config @@ -0,0 +1,4 @@ + + + + diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Molality.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Molality.g.cs new file mode 100644 index 0000000000..60a5ac28d2 --- /dev/null +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Molality.g.cs @@ -0,0 +1,175 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using UnitsNet.Units; + +namespace UnitsNet +{ + /// + /// + /// Molality is a measure of the amount of solute in a solution relative to a given mass of solvent. + /// + /// + /// https://en.wikipedia.org/wiki/Molality + /// + public struct Molality + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MolalityUnit _unit; + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + public MolalityUnit Unit => _unit; + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to construct this quantity with. + /// The unit representation to construct this quantity with. + /// If value is NaN or Infinity. + public Molality(double value, MolalityUnit unit) + { + _value = value; + _unit = unit; + } + + /// + /// The base unit of Duration, which is Second. All conversions go via this value. + /// + public static MolalityUnit BaseUnit { get; } = MolalityUnit.MolePerKilogram; + + /// + /// Represents the largest possible value of Duration + /// + public static Molality MaxValue { get; } = new Molality(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Duration + /// + public static Molality MinValue { get; } = new Molality(double.MinValue, BaseUnit); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Second. + /// + public static Molality Zero { get; } = new Molality(0, BaseUnit); + #region Conversion Properties + + /// + /// Gets a value of this quantity converted into + /// + public double MolesPerGram => As(MolalityUnit.MolePerGram); + + /// + /// Gets a value of this quantity converted into + /// + public double MolesPerKilogram => As(MolalityUnit.MolePerKilogram); + + #endregion + + #region Static Factory Methods + + /// + /// Creates a from . + /// + /// If value is NaN or Infinity. + public static Molality FromMolesPerGram(double molespergram) => new Molality(molespergram, MolalityUnit.MolePerGram); + + /// + /// Creates a from . + /// + /// If value is NaN or Infinity. + public static Molality FromMolesPerKilogram(double molesperkilogram) => new Molality(molesperkilogram, MolalityUnit.MolePerKilogram); + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// Molality unit value. + public static Molality From(double value, MolalityUnit fromUnit) + { + return new Molality(value, fromUnit); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MolalityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Molality ToUnit(MolalityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Molality(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + MolalityUnit.MolePerGram => _value / 1e-3, + MolalityUnit.MolePerKilogram => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(MolalityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + MolalityUnit.MolePerGram => baseUnitValue * 1e-3, + MolalityUnit.MolePerKilogram => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion + } +} + diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/MolalityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/MolalityUnit.g.cs new file mode 100644 index 0000000000..e3644e273d --- /dev/null +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/MolalityUnit.g.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum MolalityUnit + { + MolePerGram = 4, + MolePerKilogram = 1, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.NanoFramework/GeneratedCode/UnitsNet.nanoFramework.sln b/UnitsNet.NanoFramework/GeneratedCode/UnitsNet.nanoFramework.sln index f89c957a9e..a69d7513b2 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/UnitsNet.nanoFramework.sln +++ b/UnitsNet.NanoFramework/GeneratedCode/UnitsNet.nanoFramework.sln @@ -142,6 +142,8 @@ Project("{d608a2b1-6ead-4383-a205-ad1ce69d9ef7}") = "MassFraction", "MassFractio EndProject Project("{d608a2b1-6ead-4383-a205-ad1ce69d9ef7}") = "MassMomentOfInertia", "MassMomentOfInertia\MassMomentOfInertia.nfproj", "{6218c061-3905-79b2-d3bc-bb7b8fc77a69}" EndProject +Project("{d608a2b1-6ead-4383-a205-ad1ce69d9ef7}") = "Molality", "Molality\Molality.nfproj", "{589b202c-e638-5c93-fefe-e1e3bab4a493}" +EndProject Project("{d608a2b1-6ead-4383-a205-ad1ce69d9ef7}") = "MolarEnergy", "MolarEnergy\MolarEnergy.nfproj", "{9b77d4e0-863d-4a74-c30a-56f7b2bb7cb7}" EndProject Project("{d608a2b1-6ead-4383-a205-ad1ce69d9ef7}") = "MolarEntropy", "MolarEntropy\MolarEntropy.nfproj", "{2053731b-90f5-5141-d15e-8d7be8c2662f}" @@ -668,6 +670,12 @@ Global {6218c061-3905-79b2-d3bc-bb7b8fc77a69}.Release|Any CPU.ActiveCfg = Release|Any CPU {6218c061-3905-79b2-d3bc-bb7b8fc77a69}.Release|Any CPU.Build.0 = Release|Any CPU {6218c061-3905-79b2-d3bc-bb7b8fc77a69}.Release|Any CPU.Deploy.0 = Release|Any CPU +{589b202c-e638-5c93-fefe-e1e3bab4a493}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{589b202c-e638-5c93-fefe-e1e3bab4a493}.Debug|Any CPU.Build.0 = Debug|Any CPU +{589b202c-e638-5c93-fefe-e1e3bab4a493}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{589b202c-e638-5c93-fefe-e1e3bab4a493}.Release|Any CPU.ActiveCfg = Release|Any CPU +{589b202c-e638-5c93-fefe-e1e3bab4a493}.Release|Any CPU.Build.0 = Release|Any CPU +{589b202c-e638-5c93-fefe-e1e3bab4a493}.Release|Any CPU.Deploy.0 = Release|Any CPU {9b77d4e0-863d-4a74-c30a-56f7b2bb7cb7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9b77d4e0-863d-4a74-c30a-56f7b2bb7cb7}.Debug|Any CPU.Build.0 = Debug|Any CPU {9b77d4e0-863d-4a74-c30a-56f7b2bb7cb7}.Debug|Any CPU.Deploy.0 = Debug|Any CPU diff --git a/UnitsNet.NumberExtensions.Tests/GeneratedCode/NumberToMolalityExtensionsTest.g.cs b/UnitsNet.NumberExtensions.Tests/GeneratedCode/NumberToMolalityExtensionsTest.g.cs new file mode 100644 index 0000000000..ed269bda36 --- /dev/null +++ b/UnitsNet.NumberExtensions.Tests/GeneratedCode/NumberToMolalityExtensionsTest.g.cs @@ -0,0 +1,36 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using UnitsNet.NumberExtensions.NumberToMolality; +using Xunit; + +namespace UnitsNet.Tests +{ + public class NumberToMolalityExtensionsTests + { + [Fact] + public void NumberToMolesPerGramTest() => + Assert.Equal(Molality.FromMolesPerGram(2), 2.MolesPerGram()); + + [Fact] + public void NumberToMolesPerKilogramTest() => + Assert.Equal(Molality.FromMolesPerKilogram(2), 2.MolesPerKilogram()); + + } +} diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolalityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolalityExtensions.g.cs new file mode 100644 index 0000000000..5082f28861 --- /dev/null +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolalityExtensions.g.cs @@ -0,0 +1,52 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; + +#if NET7_0_OR_GREATER +using System.Numerics; +#endif + +#nullable enable + +namespace UnitsNet.NumberExtensions.NumberToMolality +{ + /// + /// A number to Molality Extensions + /// + public static class NumberToMolalityExtensions + { + /// + public static Molality MolesPerGram(this T value) + where T : notnull +#if NET7_0_OR_GREATER + , INumber +#endif + => Molality.FromMolesPerGram(Convert.ToDouble(value)); + + /// + public static Molality MolesPerKilogram(this T value) + where T : notnull +#if NET7_0_OR_GREATER + , INumber +#endif + => Molality.FromMolesPerKilogram(Convert.ToDouble(value)); + + } +} diff --git a/UnitsNet.Tests/CustomCode/MolalityTests.cs b/UnitsNet.Tests/CustomCode/MolalityTests.cs new file mode 100644 index 0000000000..2817ef19e3 --- /dev/null +++ b/UnitsNet.Tests/CustomCode/MolalityTests.cs @@ -0,0 +1,15 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; + +namespace UnitsNet.Tests.CustomCode +{ + public class MolalityTests : MolalityTestsBase + { + protected override bool SupportsSIUnitSystem => true; + + protected override double MolesPerKilogramInOneMolePerKilogram => 1; + protected override double MolesPerGramInOneMolePerKilogram => 1e-3; + } +} diff --git a/UnitsNet.Tests/GeneratedCode/IQuantityTests.g.cs b/UnitsNet.Tests/GeneratedCode/IQuantityTests.g.cs index 50b1767879..c1a2c2e2d2 100644 --- a/UnitsNet.Tests/GeneratedCode/IQuantityTests.g.cs +++ b/UnitsNet.Tests/GeneratedCode/IQuantityTests.g.cs @@ -104,6 +104,7 @@ void Assertion(int expectedValue, Enum expectedUnit, IQuantity quantity) Assertion(3, MassFluxUnit.KilogramPerSecondPerSquareMillimeter, Quantity.From(3, MassFluxUnit.KilogramPerSecondPerSquareMillimeter)); Assertion(3, MassFractionUnit.Percent, Quantity.From(3, MassFractionUnit.Percent)); Assertion(3, MassMomentOfInertiaUnit.TonneSquareMilimeter, Quantity.From(3, MassMomentOfInertiaUnit.TonneSquareMilimeter)); + Assertion(3, MolalityUnit.MolePerKilogram, Quantity.From(3, MolalityUnit.MolePerKilogram)); Assertion(3, MolarEnergyUnit.MegajoulePerMole, Quantity.From(3, MolarEnergyUnit.MegajoulePerMole)); Assertion(3, MolarEntropyUnit.MegajoulePerMoleKelvin, Quantity.From(3, MolarEntropyUnit.MegajoulePerMoleKelvin)); Assertion(3, MolarFlowUnit.PoundMolePerSecond, Quantity.From(3, MolarFlowUnit.PoundMolePerSecond)); @@ -231,6 +232,7 @@ public void QuantityInfo_IsSameAsStaticInfoProperty() Assertion(MassFlux.Info, MassFlux.Zero); Assertion(MassFraction.Info, MassFraction.Zero); Assertion(MassMomentOfInertia.Info, MassMomentOfInertia.Zero); + Assertion(Molality.Info, Molality.Zero); Assertion(MolarEnergy.Info, MolarEnergy.Zero); Assertion(MolarEntropy.Info, MolarEntropy.Zero); Assertion(MolarFlow.Info, MolarFlow.Zero); @@ -358,6 +360,7 @@ public void Dimensions_IsSameAsStaticBaseDimensions() Assertion(MassFlux.BaseDimensions, MassFlux.Zero); Assertion(MassFraction.BaseDimensions, MassFraction.Zero); Assertion(MassMomentOfInertia.BaseDimensions, MassMomentOfInertia.Zero); + Assertion(Molality.BaseDimensions, Molality.Zero); Assertion(MolarEnergy.BaseDimensions, MolarEnergy.Zero); Assertion(MolarEntropy.BaseDimensions, MolarEntropy.Zero); Assertion(MolarFlow.BaseDimensions, MolarFlow.Zero); diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MolalityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MolalityTestsBase.g.cs new file mode 100644 index 0000000000..d8dec9a2d0 --- /dev/null +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolalityTestsBase.g.cs @@ -0,0 +1,668 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Threading; +using UnitsNet.Tests.TestsBase; +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 Molality. + /// +// ReSharper disable once PartialTypeWithSinglePart + public abstract partial class MolalityTestsBase : QuantityTestsBase + { + protected abstract double MolesPerGramInOneMolePerKilogram { get; } + protected abstract double MolesPerKilogramInOneMolePerKilogram { get; } + +// ReSharper disable VirtualMemberNeverOverriden.Global + protected virtual double MolesPerGramTolerance { get { return 1e-5; } } + protected virtual double MolesPerKilogramTolerance { get { return 1e-5; } } +// ReSharper restore VirtualMemberNeverOverriden.Global + + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MolalityUnit unit) + { + return unit switch + { + MolalityUnit.MolePerGram => (MolesPerGramInOneMolePerKilogram, MolesPerGramTolerance), + MolalityUnit.MolePerKilogram => (MolesPerKilogramInOneMolePerKilogram, MolesPerKilogramTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { MolalityUnit.MolePerGram }, + new object[] { MolalityUnit.MolePerKilogram }, + }; + + [Fact] + public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() + { + var quantity = new Molality(); + Assert.Equal(0, quantity.Value); + Assert.Equal(MolalityUnit.MolePerKilogram, quantity.Unit); + } + + [Fact] + public void Ctor_WithInfinityValue_ThrowsArgumentException() + { + Assert.Throws(() => new Molality(double.PositiveInfinity, MolalityUnit.MolePerKilogram)); + Assert.Throws(() => new Molality(double.NegativeInfinity, MolalityUnit.MolePerKilogram)); + } + + [Fact] + public void Ctor_WithNaNValue_ThrowsArgumentException() + { + Assert.Throws(() => new Molality(double.NaN, MolalityUnit.MolePerKilogram)); + } + + [Fact] + public void Ctor_NullAsUnitSystem_ThrowsArgumentNullException() + { + Assert.Throws(() => new Molality(value: 1, unitSystem: null)); + } + + [Fact] + public void Ctor_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() + { + Func TestCode = () => new Molality(value: 1, unitSystem: UnitSystem.SI); + if (SupportsSIUnitSystem) + { + var quantity = (Molality) TestCode(); + Assert.Equal(1, quantity.Value); + } + else + { + Assert.Throws(TestCode); + } + } + + [Fact] + public void Molality_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() + { + var quantity = new Molality(1, MolalityUnit.MolePerKilogram); + + QuantityInfo quantityInfo = quantity.QuantityInfo; + + Assert.Equal(Molality.Zero, quantityInfo.Zero); + Assert.Equal("Molality", quantityInfo.Name); + + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); + var unitNames = units.Select(x => x.ToString()); + } + + [Fact] + public void MolePerKilogramToMolalityUnits() + { + Molality moleperkilogram = Molality.FromMolesPerKilogram(1); + AssertEx.EqualTolerance(MolesPerGramInOneMolePerKilogram, moleperkilogram.MolesPerGram, MolesPerGramTolerance); + AssertEx.EqualTolerance(MolesPerKilogramInOneMolePerKilogram, moleperkilogram.MolesPerKilogram, MolesPerKilogramTolerance); + } + + [Fact] + public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() + { + var quantity00 = Molality.From(1, MolalityUnit.MolePerGram); + AssertEx.EqualTolerance(1, quantity00.MolesPerGram, MolesPerGramTolerance); + Assert.Equal(MolalityUnit.MolePerGram, quantity00.Unit); + + var quantity01 = Molality.From(1, MolalityUnit.MolePerKilogram); + AssertEx.EqualTolerance(1, quantity01.MolesPerKilogram, MolesPerKilogramTolerance); + Assert.Equal(MolalityUnit.MolePerKilogram, quantity01.Unit); + + } + + [Fact] + public void FromMolesPerKilogram_WithInfinityValue_ThrowsArgumentException() + { + Assert.Throws(() => Molality.FromMolesPerKilogram(double.PositiveInfinity)); + Assert.Throws(() => Molality.FromMolesPerKilogram(double.NegativeInfinity)); + } + + [Fact] + public void FromMolesPerKilogram_WithNanValue_ThrowsArgumentException() + { + Assert.Throws(() => Molality.FromMolesPerKilogram(double.NaN)); + } + + [Fact] + public void As() + { + var moleperkilogram = Molality.FromMolesPerKilogram(1); + AssertEx.EqualTolerance(MolesPerGramInOneMolePerKilogram, moleperkilogram.As(MolalityUnit.MolePerGram), MolesPerGramTolerance); + AssertEx.EqualTolerance(MolesPerKilogramInOneMolePerKilogram, moleperkilogram.As(MolalityUnit.MolePerKilogram), MolesPerKilogramTolerance); + } + + [Fact] + public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() + { + var quantity = new Molality(value: 1, unit: Molality.BaseUnit); + Func AsWithSIUnitSystem = () => quantity.As(UnitSystem.SI); + + if (SupportsSIUnitSystem) + { + var value = Convert.ToDouble(AsWithSIUnitSystem()); + Assert.Equal(1, value); + } + else + { + Assert.Throws(AsWithSIUnitSystem); + } + } + + [Fact] + public void Parse() + { + try + { + var parsed = Molality.Parse("1 mol/g", CultureInfo.GetCultureInfo("en-US")); + AssertEx.EqualTolerance(1, parsed.MolesPerGram, MolesPerGramTolerance); + Assert.Equal(MolalityUnit.MolePerGram, parsed.Unit); + } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } + + try + { + var parsed = Molality.Parse("1 mol/kg", CultureInfo.GetCultureInfo("en-US")); + AssertEx.EqualTolerance(1, parsed.MolesPerKilogram, MolesPerKilogramTolerance); + Assert.Equal(MolalityUnit.MolePerKilogram, parsed.Unit); + } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } + + } + + [Fact] + public void TryParse() + { + { + Assert.True(Molality.TryParse("1 mol/g", CultureInfo.GetCultureInfo("en-US"), out var parsed)); + AssertEx.EqualTolerance(1, parsed.MolesPerGram, MolesPerGramTolerance); + Assert.Equal(MolalityUnit.MolePerGram, parsed.Unit); + } + + { + Assert.True(Molality.TryParse("1 mol/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); + AssertEx.EqualTolerance(1, parsed.MolesPerKilogram, MolesPerKilogramTolerance); + Assert.Equal(MolalityUnit.MolePerKilogram, parsed.Unit); + } + + } + + [Fact] + public void ParseUnit() + { + try + { + var parsedUnit = Molality.ParseUnit("mol/g", CultureInfo.GetCultureInfo("en-US")); + Assert.Equal(MolalityUnit.MolePerGram, parsedUnit); + } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } + + try + { + var parsedUnit = Molality.ParseUnit("mol/kg", CultureInfo.GetCultureInfo("en-US")); + Assert.Equal(MolalityUnit.MolePerKilogram, parsedUnit); + } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } + + } + + [Fact] + public void TryParseUnit() + { + { + Assert.True(Molality.TryParseUnit("mol/g", CultureInfo.GetCultureInfo("en-US"), out var parsedUnit)); + Assert.Equal(MolalityUnit.MolePerGram, parsedUnit); + } + + { + Assert.True(Molality.TryParseUnit("mol/kg", CultureInfo.GetCultureInfo("en-US"), out var parsedUnit)); + Assert.Equal(MolalityUnit.MolePerKilogram, parsedUnit); + } + + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(MolalityUnit unit) + { + var inBaseUnits = Molality.From(1.0, Molality.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); + + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(MolalityUnit unit) + { + var quantity = Molality.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MolalityUnit unit) + { + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Molality.Units.First(u => u != Molality.BaseUnit); + + var quantity = Molality.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public virtual void ToUnit_FromDefaultQuantity_ReturnsQuantityWithGivenUnit(MolalityUnit unit) + { + var quantity = default(Molality); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); + } + + [Fact] + public void ConversionRoundTrip() + { + Molality moleperkilogram = Molality.FromMolesPerKilogram(1); + AssertEx.EqualTolerance(1, Molality.FromMolesPerGram(moleperkilogram.MolesPerGram).MolesPerKilogram, MolesPerGramTolerance); + AssertEx.EqualTolerance(1, Molality.FromMolesPerKilogram(moleperkilogram.MolesPerKilogram).MolesPerKilogram, MolesPerKilogramTolerance); + } + + [Fact] + public void ArithmeticOperators() + { + Molality v = Molality.FromMolesPerKilogram(1); + AssertEx.EqualTolerance(-1, -v.MolesPerKilogram, MolesPerKilogramTolerance); + AssertEx.EqualTolerance(2, (Molality.FromMolesPerKilogram(3)-v).MolesPerKilogram, MolesPerKilogramTolerance); + AssertEx.EqualTolerance(2, (v + v).MolesPerKilogram, MolesPerKilogramTolerance); + AssertEx.EqualTolerance(10, (v*10).MolesPerKilogram, MolesPerKilogramTolerance); + AssertEx.EqualTolerance(10, (10*v).MolesPerKilogram, MolesPerKilogramTolerance); + AssertEx.EqualTolerance(2, (Molality.FromMolesPerKilogram(10)/5).MolesPerKilogram, MolesPerKilogramTolerance); + AssertEx.EqualTolerance(2, Molality.FromMolesPerKilogram(10)/Molality.FromMolesPerKilogram(5), MolesPerKilogramTolerance); + } + + [Fact] + public void ComparisonOperators() + { + Molality oneMolePerKilogram = Molality.FromMolesPerKilogram(1); + Molality twoMolesPerKilogram = Molality.FromMolesPerKilogram(2); + + Assert.True(oneMolePerKilogram < twoMolesPerKilogram); + Assert.True(oneMolePerKilogram <= twoMolesPerKilogram); + Assert.True(twoMolesPerKilogram > oneMolePerKilogram); + Assert.True(twoMolesPerKilogram >= oneMolePerKilogram); + + Assert.False(oneMolePerKilogram > twoMolesPerKilogram); + Assert.False(oneMolePerKilogram >= twoMolesPerKilogram); + Assert.False(twoMolesPerKilogram < oneMolePerKilogram); + Assert.False(twoMolesPerKilogram <= oneMolePerKilogram); + } + + [Fact] + public void CompareToIsImplemented() + { + Molality moleperkilogram = Molality.FromMolesPerKilogram(1); + Assert.Equal(0, moleperkilogram.CompareTo(moleperkilogram)); + Assert.True(moleperkilogram.CompareTo(Molality.Zero) > 0); + Assert.True(Molality.Zero.CompareTo(moleperkilogram) < 0); + } + + [Fact] + public void CompareToThrowsOnTypeMismatch() + { + Molality moleperkilogram = Molality.FromMolesPerKilogram(1); + Assert.Throws(() => moleperkilogram.CompareTo(new object())); + } + + [Fact] + public void CompareToThrowsOnNull() + { + Molality moleperkilogram = Molality.FromMolesPerKilogram(1); + Assert.Throws(() => moleperkilogram.CompareTo(null)); + } + + [Theory] + [InlineData(1, MolalityUnit.MolePerKilogram, 1, MolalityUnit.MolePerKilogram, true)] // Same value and unit. + [InlineData(1, MolalityUnit.MolePerKilogram, 2, MolalityUnit.MolePerKilogram, false)] // Different value. + [InlineData(2, MolalityUnit.MolePerKilogram, 1, MolalityUnit.MolePerGram, false)] // Different value and unit. + [InlineData(1, MolalityUnit.MolePerKilogram, 1, MolalityUnit.MolePerGram, false)] // Different unit. + public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, MolalityUnit unitA, double valueB, MolalityUnit unitB, bool expectEqual) + { + var a = new Molality(valueA, unitA); + var b = new Molality(valueB, unitB); + + // Operator overloads. + Assert.Equal(expectEqual, a == b); + Assert.Equal(expectEqual, b == a); + Assert.Equal(!expectEqual, a != b); + Assert.Equal(!expectEqual, b != a); + + // IEquatable + Assert.Equal(expectEqual, a.Equals(b)); + Assert.Equal(expectEqual, b.Equals(a)); + + // IEquatable + Assert.Equal(expectEqual, a.Equals((object)b)); + Assert.Equal(expectEqual, b.Equals((object)a)); + } + + [Fact] + public void Equals_Null_ReturnsFalse() + { + var a = Molality.Zero; + + Assert.False(a.Equals((object)null)); + + // "The result of the expression is always 'false'..." + #pragma warning disable CS8073 + Assert.False(a == null); + Assert.False(null == a); + Assert.True(a != null); + Assert.True(null != a); + #pragma warning restore CS8073 + } + + [Fact] + public void Equals_RelativeTolerance_IsImplemented() + { + var v = Molality.FromMolesPerKilogram(1); + Assert.True(v.Equals(Molality.FromMolesPerKilogram(1), MolesPerKilogramTolerance, ComparisonType.Relative)); + Assert.False(v.Equals(Molality.Zero, MolesPerKilogramTolerance, ComparisonType.Relative)); + } + + [Fact] + public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + { + var v = Molality.FromMolesPerKilogram(1); + Assert.Throws(() => v.Equals(Molality.FromMolesPerKilogram(1), -1, ComparisonType.Relative)); + } + + [Fact] + public void EqualsReturnsFalseOnTypeMismatch() + { + Molality moleperkilogram = Molality.FromMolesPerKilogram(1); + Assert.False(moleperkilogram.Equals(new object())); + } + + [Fact] + public void EqualsReturnsFalseOnNull() + { + Molality moleperkilogram = Molality.FromMolesPerKilogram(1); + Assert.False(moleperkilogram.Equals(null)); + } + + [Fact] + public void HasAtLeastOneAbbreviationSpecified() + { + var units = Enum.GetValues(typeof(MolalityUnit)).Cast(); + foreach (var unit in units) + { + var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); + } + } + + [Fact] + public void BaseDimensionsShouldNeverBeNull() + { + Assert.False(Molality.BaseDimensions is null); + } + + [Fact] + public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() + { + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); + try { + Assert.Equal("1 mol/g", new Molality(1, MolalityUnit.MolePerGram).ToString()); + Assert.Equal("1 mol/kg", new Molality(1, MolalityUnit.MolePerKilogram).ToString()); + } + finally + { + Thread.CurrentThread.CurrentCulture = prevCulture; + } + } + + [Fact] + public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCultureSinceThereAreNoMappings() + { + // Chose this culture, because we don't currently have any abbreviations mapped for that culture and we expect the en-US to be used as fallback. + var swedishCulture = CultureInfo.GetCultureInfo("sv-SE"); + + Assert.Equal("1 mol/g", new Molality(1, MolalityUnit.MolePerGram).ToString(swedishCulture)); + Assert.Equal("1 mol/kg", new Molality(1, MolalityUnit.MolePerKilogram).ToString(swedishCulture)); + } + + [Fact] + public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() + { + var oldCulture = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; + Assert.Equal("0.1 mol/kg", new Molality(0.123456, MolalityUnit.MolePerKilogram).ToString("s1")); + Assert.Equal("0.12 mol/kg", new Molality(0.123456, MolalityUnit.MolePerKilogram).ToString("s2")); + Assert.Equal("0.123 mol/kg", new Molality(0.123456, MolalityUnit.MolePerKilogram).ToString("s3")); + Assert.Equal("0.1235 mol/kg", new Molality(0.123456, MolalityUnit.MolePerKilogram).ToString("s4")); + } + finally + { + CultureInfo.CurrentCulture = oldCulture; + } + } + + [Fact] + public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixForGivenCulture() + { + var culture = CultureInfo.InvariantCulture; + Assert.Equal("0.1 mol/kg", new Molality(0.123456, MolalityUnit.MolePerKilogram).ToString("s1", culture)); + Assert.Equal("0.12 mol/kg", new Molality(0.123456, MolalityUnit.MolePerKilogram).ToString("s2", culture)); + Assert.Equal("0.123 mol/kg", new Molality(0.123456, MolalityUnit.MolePerKilogram).ToString("s3", culture)); + Assert.Equal("0.1235 mol/kg", new Molality(0.123456, MolalityUnit.MolePerKilogram).ToString("s4", culture)); + } + + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) + { + var quantity = Molality.FromMolesPerKilogram(1.0); + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); + + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); + } + + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); + } + + [Fact] + public void Convert_ToBool_ThrowsInvalidCastException() + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Throws(() => Convert.ToBoolean(quantity)); + } + + [Fact] + public void Convert_ToByte_EqualsValueAsSameType() + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + } + + [Fact] + public void Convert_ToChar_ThrowsInvalidCastException() + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Throws(() => Convert.ToChar(quantity)); + } + + [Fact] + public void Convert_ToDateTime_ThrowsInvalidCastException() + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Throws(() => Convert.ToDateTime(quantity)); + } + + [Fact] + public void Convert_ToDecimal_EqualsValueAsSameType() + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); + } + + [Fact] + public void Convert_ToDouble_EqualsValueAsSameType() + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); + } + + [Fact] + public void Convert_ToInt16_EqualsValueAsSameType() + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + } + + [Fact] + public void Convert_ToInt32_EqualsValueAsSameType() + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + } + + [Fact] + public void Convert_ToInt64_EqualsValueAsSameType() + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + } + + [Fact] + public void Convert_ToSByte_EqualsValueAsSameType() + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + } + + [Fact] + public void Convert_ToSingle_EqualsValueAsSameType() + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + } + + [Fact] + public void Convert_ToString_EqualsToString() + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); + } + + [Fact] + public void Convert_ToUInt16_EqualsValueAsSameType() + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + } + + [Fact] + public void Convert_ToUInt32_EqualsValueAsSameType() + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + } + + [Fact] + public void Convert_ToUInt64_EqualsValueAsSameType() + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + } + + [Fact] + public void Convert_ChangeType_SelfType_EqualsSelf() + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Molality))); + } + + [Fact] + public void Convert_ChangeType_UnitType_EqualsUnit() + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MolalityUnit))); + } + + [Fact] + public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Equal(Molality.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); + } + + [Fact] + public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Equal(Molality.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); + } + + [Fact] + public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); + } + + [Fact] + public void GetHashCode_Equals() + { + var quantity = Molality.FromMolesPerKilogram(1.0); + Assert.Equal(new {Molality.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + } + + [Theory] + [InlineData(1.0)] + [InlineData(-1.0)] + public void NegationOperator_ReturnsQuantity_WithNegatedValue(double value) + { + var quantity = Molality.FromMolesPerKilogram(value); + Assert.Equal(Molality.FromMolesPerKilogram(-value), -quantity); + } + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Molality.g.cs b/UnitsNet/GeneratedCode/Quantities/Molality.g.cs new file mode 100644 index 0000000000..44b51bcede --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Molality.g.cs @@ -0,0 +1,953 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// + /// Molality is a measure of the amount of solute in a solution relative to a given mass of solvent. + /// + /// + /// https://en.wikipedia.org/wiki/Molality + /// + [DataContract] + public readonly partial struct Molality : + IArithmeticQuantity, + IComparable, + IComparable, + IConvertible, + IEquatable, + IFormattable + { + /// + /// The numeric value this quantity was constructed with. + /// + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + [DataMember(Name = "Unit", Order = 1)] + private readonly MolalityUnit? _unit; + + static Molality() + { + BaseDimensions = new BaseDimensions(0, -1, 0, 0, 0, 1, 0); + BaseUnit = MolalityUnit.MolePerKilogram; + Units = Enum.GetValues(typeof(MolalityUnit)).Cast().ToArray(); + Zero = new Molality(0, BaseUnit); + Info = new QuantityInfo("Molality", + new UnitInfo[] + { + new UnitInfo(MolalityUnit.MolePerGram, "MolesPerGram", new BaseUnits(mass: MassUnit.Gram, amount: AmountOfSubstanceUnit.Mole), "Molality"), + new UnitInfo(MolalityUnit.MolePerKilogram, "MolesPerKilogram", new BaseUnits(mass: MassUnit.Kilogram, amount: AmountOfSubstanceUnit.Mole), "Molality"), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to construct this quantity with. + /// The unit representation to construct this quantity with. + /// If value is NaN or Infinity. + public Molality(double value, MolalityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + /// + /// Creates an instance of the quantity with the given numeric value in units compatible with the given . + /// If multiple compatible units were found, the first match is used. + /// + /// The numeric value to construct this quantity with. + /// The unit system to create the quantity with. + /// The given is null. + /// No unit was found for the given . + public Molality(double value, UnitSystem unitSystem) + { + if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); + + var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); + var firstUnitInfo = unitInfos.FirstOrDefault(); + + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); + } + + #region Static Properties + + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } + + /// + public static QuantityInfo Info { get; } + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Molality, which is MolePerKilogram. All conversions go via this value. + /// + public static MolalityUnit BaseUnit { get; } + + /// + /// All units of measurement for the Molality quantity. + /// + public static MolalityUnit[] Units { get; } + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit MolePerKilogram. + /// + public static Molality Zero { get; } + + /// + public static Molality AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// + public MolalityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + public QuantityInfo QuantityInfo => Info; + + /// + QuantityInfo IQuantity.QuantityInfo => Info; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Molality.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Gets a value of this quantity converted into + /// + public double MolesPerGram => As(MolalityUnit.MolePerGram); + + /// + /// Gets a value of this quantity converted into + /// + public double MolesPerKilogram => As(MolalityUnit.MolePerKilogram); + + #endregion + + #region Static Methods + + /// + /// Registers the default conversion functions in the given instance. + /// + /// The to register the default conversion functions in. + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: MolalityUnit -> BaseUnit + unitConverter.SetConversionFunction(MolalityUnit.MolePerGram, MolalityUnit.MolePerKilogram, quantity => quantity.ToUnit(MolalityUnit.MolePerKilogram)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction(MolalityUnit.MolePerKilogram, MolalityUnit.MolePerKilogram, quantity => quantity); + + // Register in unit converter: BaseUnit -> MolalityUnit + unitConverter.SetConversionFunction(MolalityUnit.MolePerKilogram, MolalityUnit.MolePerGram, quantity => quantity.ToUnit(MolalityUnit.MolePerGram)); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MolalityUnit 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(MolalityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Creates a from . + /// + /// If value is NaN or Infinity. + public static Molality FromMolesPerGram(QuantityValue molespergram) + { + double value = (double) molespergram; + return new Molality(value, MolalityUnit.MolePerGram); + } + + /// + /// Creates a from . + /// + /// If value is NaN or Infinity. + public static Molality FromMolesPerKilogram(QuantityValue molesperkilogram) + { + double value = (double) molesperkilogram; + return new Molality(value, MolalityUnit.MolePerKilogram); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// Molality unit value. + public static Molality From(QuantityValue value, MolalityUnit fromUnit) + { + return new Molality((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", CultureInfo.GetCultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + public static Molality Parse(string str) + { + return Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", CultureInfo.GetCultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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 Molality Parse(string str, 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", CultureInfo.GetCultureInfo("en-US")); + /// + public static bool TryParse(string? str, out Molality result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", CultureInfo.GetCultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse(string? str, IFormatProvider? provider, out Molality 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", CultureInfo.GetCultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static MolalityUnit ParseUnit(string str) + { + 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 if null. + /// + /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static MolalityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse(str, provider); + } + + /// + public static bool TryParseUnit(string str, out MolalityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider? provider, out MolalityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// Negate the value. + public static Molality operator -(Molality right) + { + return new Molality(-right.Value, right.Unit); + } + + /// Get from adding two . + public static Molality operator +(Molality left, Molality right) + { + return new Molality(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// Get from subtracting two . + public static Molality operator -(Molality left, Molality right) + { + return new Molality(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// Get from multiplying value and . + public static Molality operator *(double left, Molality right) + { + return new Molality(left * right.Value, right.Unit); + } + + /// Get from multiplying value and . + public static Molality operator *(Molality left, double right) + { + return new Molality(left.Value * right, left.Unit); + } + + /// Get from dividing by value. + public static Molality operator /(Molality left, double right) + { + return new Molality(left.Value / right, left.Unit); + } + + /// Get ratio value from dividing by . + public static double operator /(Molality left, Molality right) + { + return left.MolesPerKilogram / right.MolesPerKilogram; + } + + #endregion + + #region Equality / IComparable + + /// Returns true if less or equal to. + public static bool operator <=(Molality left, Molality right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// Returns true if greater than or equal to. + public static bool operator >=(Molality left, Molality right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// Returns true if less than. + public static bool operator <(Molality left, Molality right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// Returns true if greater than. + public static bool operator >(Molality left, Molality right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// Indicates strict equality of two quantities, where both and are exactly equal. + [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Molality other, Molality tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + public static bool operator ==(Molality left, Molality right) + { + return left.Equals(right); + } + + /// Indicates strict inequality of two quantities, where both and are exactly equal. + [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Molality other, Molality tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + public static bool operator !=(Molality left, Molality right) + { + return !(left == right); + } + + /// + /// Indicates strict equality of two quantities, where both and are exactly equal. + [Obsolete("Use Equals(Molality other, Molality tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Molality otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// + /// Indicates strict equality of two quantities, where both and are exactly equal. + [Obsolete("Use Equals(Molality other, Molality tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + public bool Equals(Molality other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// An object to compare with this instance. + /// + /// is not the same type as this instance. + /// + /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// + /// Value Meaning + /// Less than zero This instance precedes in the sort order. + /// Zero This instance occurs in the same position in the sort order as . + /// Greater than zero This instance follows in the sort order. + /// + /// + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Molality otherQuantity)) throw new ArgumentException("Expected type Molality.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// A quantity to compare with this instance. + /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// + /// Value Meaning + /// Less than zero This instance precedes in the sort order. + /// Zero This instance occurs in the same position in the sort order as . + /// Greater than zero This instance follows in the sort order. + /// + /// + public int CompareTo(Molality other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// + /// + /// Compare equality to another Molality within the given absolute or relative tolerance. + /// + /// + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a percentage of this quantity's value. will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// + /// + /// + /// + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a fixed number in this quantity's unit. will be converted into + /// this quantity's unit for comparison. + /// + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// + /// + /// + /// + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// + /// + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + [Obsolete("Use Equals(Molality other, Molality tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + public bool Equals(Molality other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); + + return UnitsNet.Comparison.Equals( + referenceValue: this.Value, + otherValue: other.As(this.Unit), + tolerance: tolerance, + comparisonType: ComparisonType.Absolute); + } + + /// + public bool Equals(IQuantity? other, IQuantity tolerance) + { + return other is Molality otherTyped + && (tolerance is Molality toleranceTyped + ? true + : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Molality'.", nameof(tolerance))) + && Equals(otherTyped, toleranceTyped); + } + + /// + public bool Equals(Molality other, Molality tolerance) + { + return UnitsNet.Comparison.Equals( + referenceValue: this.Value, + otherValue: other.As(this.Unit), + tolerance: tolerance.As(this.Unit), + comparisonType: ComparisonType.Absolute); + } + + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Molality. + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MolalityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// + public double As(UnitSystem unitSystem) + { + if (unitSystem is null) + throw new ArgumentNullException(nameof(unitSystem)); + + var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); + + var firstUnitInfo = unitInfos.FirstOrDefault(); + if (firstUnitInfo == null) + throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); + + return As(firstUnitInfo.Value); + } + + /// + double IQuantity.As(Enum unit) + { + if (!(unit is MolalityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolalityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// + double IValueQuantity.As(Enum unit) + { + if (!(unit is MolalityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolalityUnit)} is supported.", nameof(unit)); + + return As(typedUnit); + } + + /// + /// Converts this Molality to another Molality with the unit representation . + /// + /// The unit to convert to. + /// A Molality with the specified unit. + public Molality ToUnit(MolalityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this to another using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Molality with the specified unit. + public Molality ToUnit(MolalityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Molality), Unit, typeof(Molality), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Molality)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// + /// Attempts to convert this to another with the unit representation . + /// + /// The unit to convert to. + /// The converted in , if successful. + /// True if successful, otherwise false. + private bool TryToUnit(MolalityUnit unit, [NotNullWhen(true)] out Molality? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Molality? convertedOrNull = (Unit, unit) switch + { + // MolalityUnit -> BaseUnit + (MolalityUnit.MolePerGram, MolalityUnit.MolePerKilogram) => new Molality(_value / 1e-3, MolalityUnit.MolePerKilogram), + + // BaseUnit -> MolalityUnit + (MolalityUnit.MolePerKilogram, MolalityUnit.MolePerGram) => new Molality(_value * 1e-3, MolalityUnit.MolePerGram), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is MolalityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolalityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// + public Molality ToUnit(UnitSystem unitSystem) + { + if (unitSystem is null) + throw new ArgumentNullException(nameof(unitSystem)); + + var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); + + var firstUnitInfo = unitInfos.FirstOrDefault(); + if (firstUnitInfo == null) + throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); + + return ToUnit(firstUnitInfo.Value); + } + + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + + /// + IQuantity IQuantity.ToUnit(MolalityUnit unit) => ToUnit(unit); + + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + + /// + IValueQuantity IValueQuantity.ToUnit(Enum unit) + { + if (unit is not MolalityUnit typedUnit) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolalityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit); + } + + /// + IValueQuantity IValueQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + + #endregion + + #region ToString Methods + + /// + /// Gets the default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString("g"); + } + + /// + /// Gets the default string representation of value and unit using the given format provider. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// + /// + /// Gets the string representation of this instance in the specified format string using . + /// + /// The format string. + /// The string representation. + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// + /// + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// + /// The format string. + /// Format to use for localization and number formatting. Defaults to if null. + /// The string representation. + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Molality)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Molality)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Molality)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Molality)) + return this; + else if (conversionType == typeof(MolalityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Molality.Info; + else if (conversionType == typeof(BaseDimensions)) + return Molality.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Molality)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet/GeneratedCode/Quantity.g.cs b/UnitsNet/GeneratedCode/Quantity.g.cs index 5236f4b15a..e65f722d6b 100644 --- a/UnitsNet/GeneratedCode/Quantity.g.cs +++ b/UnitsNet/GeneratedCode/Quantity.g.cs @@ -108,6 +108,7 @@ public partial class Quantity { "MassFlux", MassFlux.Info }, { "MassFraction", MassFraction.Info }, { "MassMomentOfInertia", MassMomentOfInertia.Info }, + { "Molality", Molality.Info }, { "MolarEnergy", MolarEnergy.Info }, { "MolarEntropy", MolarEntropy.Info }, { "MolarFlow", MolarFlow.Info }, @@ -240,6 +241,7 @@ public static IQuantity FromQuantityInfo(QuantityInfo quantityInfo, QuantityValu "MassFlux" => MassFlux.From(value, MassFlux.BaseUnit), "MassFraction" => MassFraction.From(value, MassFraction.BaseUnit), "MassMomentOfInertia" => MassMomentOfInertia.From(value, MassMomentOfInertia.BaseUnit), + "Molality" => Molality.From(value, Molality.BaseUnit), "MolarEnergy" => MolarEnergy.From(value, MolarEnergy.BaseUnit), "MolarEntropy" => MolarEntropy.From(value, MolarEntropy.BaseUnit), "MolarFlow" => MolarFlow.From(value, MolarFlow.BaseUnit), @@ -375,6 +377,7 @@ public static bool TryFrom(QuantityValue value, Enum? unit, [NotNullWhen(true)] MassFluxUnit massFluxUnit => MassFlux.From(value, massFluxUnit), MassFractionUnit massFractionUnit => MassFraction.From(value, massFractionUnit), MassMomentOfInertiaUnit massMomentOfInertiaUnit => MassMomentOfInertia.From(value, massMomentOfInertiaUnit), + MolalityUnit molalityUnit => Molality.From(value, molalityUnit), MolarEnergyUnit molarEnergyUnit => MolarEnergy.From(value, molarEnergyUnit), MolarEntropyUnit molarEntropyUnit => MolarEntropy.From(value, molarEntropyUnit), MolarFlowUnit molarFlowUnit => MolarFlow.From(value, molarFlowUnit), @@ -520,6 +523,7 @@ public static bool TryParse(IFormatProvider? formatProvider, Type quantityType, Type _ when quantityType == typeof(MassFlux) => parser.TryParse(quantityString, formatProvider, MassFlux.From, out quantity), Type _ when quantityType == typeof(MassFraction) => parser.TryParse(quantityString, formatProvider, MassFraction.From, out quantity), Type _ when quantityType == typeof(MassMomentOfInertia) => parser.TryParse(quantityString, formatProvider, MassMomentOfInertia.From, out quantity), + Type _ when quantityType == typeof(Molality) => parser.TryParse(quantityString, formatProvider, Molality.From, out quantity), Type _ when quantityType == typeof(MolarEnergy) => parser.TryParse(quantityString, formatProvider, MolarEnergy.From, out quantity), Type _ when quantityType == typeof(MolarEntropy) => parser.TryParse(quantityString, formatProvider, MolarEntropy.From, out quantity), Type _ when quantityType == typeof(MolarFlow) => parser.TryParse(quantityString, formatProvider, MolarFlow.From, out quantity), @@ -646,6 +650,7 @@ internal static IEnumerable GetQuantityTypes() yield return typeof(MassFlux); yield return typeof(MassFraction); yield return typeof(MassMomentOfInertia); + yield return typeof(Molality); yield return typeof(MolarEnergy); yield return typeof(MolarEntropy); yield return typeof(MolarFlow); diff --git a/UnitsNet/GeneratedCode/Resources/Molality.restext b/UnitsNet/GeneratedCode/Resources/Molality.restext new file mode 100644 index 0000000000..03a849f4c7 --- /dev/null +++ b/UnitsNet/GeneratedCode/Resources/Molality.restext @@ -0,0 +1,2 @@ +MolesPerGram=mol/g +MolesPerKilogram=mol/kg diff --git a/UnitsNet/GeneratedCode/Units/MolalityUnit.g.cs b/UnitsNet/GeneratedCode/Units/MolalityUnit.g.cs new file mode 100644 index 0000000000..e3644e273d --- /dev/null +++ b/UnitsNet/GeneratedCode/Units/MolalityUnit.g.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum MolalityUnit + { + MolePerGram = 4, + MolePerKilogram = 1, + } + + #pragma warning restore 1591 +}