diff --git a/Common/UnitDefinitions/FuelEfficiency.json b/Common/UnitDefinitions/FuelEfficiency.json new file mode 100644 index 0000000000..2da60218f7 --- /dev/null +++ b/Common/UnitDefinitions/FuelEfficiency.json @@ -0,0 +1,55 @@ +{ + "Name": "FuelEfficiency", + "BaseUnit": "LiterPer100Kilometers", + "XmlDoc": "Fuel efficiency is a form of thermal efficiency, meaning the ratio from effort to result of a process that converts chemical potential energy contained in a carrier (fuel) into kinetic energy or work. Fuel economy is stated as \"fuel consumption\" in liters per 100 kilometers (L/100 km). In countries using non-metric system, fuel economy is expressed in miles per gallon (mpg) (imperial galon or US galon).", + "XmlDocRemarks": "https://en.wikipedia.org/wiki/Fuel_efficiency", + "Units": [{ + "SingularName": "LiterPer100Kilometers", + "PluralName": "LitersPer100Kilometers", + "FromUnitToBaseFunc": "x", + "FromBaseToUnitFunc": "x", + "Localization": [{ + "Culture": "en-US", + "Abbreviations": [ + "L/100km" + ] + }] + }, + { + "SingularName": "MilePerUsGallon", + "PluralName": "MilesPerUsGallon", + "FromUnitToBaseFunc": "(100*3.785411784)/(1.609344*x)", + "FromBaseToUnitFunc": "(100*3.785411784)/(1.609344*x)", + "Localization": [{ + "Culture": "en-US", + "Abbreviations": [ + "mpg (U.S.)" + ] + }] + }, + { + "SingularName": "MilePerUkGallon", + "PluralName": "MilesPerUkGallon", + "FromUnitToBaseFunc": "(100*4.54609188)/(1.609344*x)", + "FromBaseToUnitFunc": "(100*4.54609188)/(1.609344*x)", + "Localization": [{ + "Culture": "en-US", + "Abbreviations": [ + "mpg (imp.)" + ] + }] + }, + { + "SingularName": "KilometerPerLiter", + "PluralName": "KilometersPerLiters", + "FromUnitToBaseFunc": "100/x", + "FromBaseToUnitFunc": "100/x", + "Localization": [{ + "Culture": "en-US", + "Abbreviations": [ + "km/L" + ] + }] + } + ] + } \ No newline at end of file diff --git a/UnitsNet.Tests/CustomCode/FuelEfficiencyTests.cs b/UnitsNet.Tests/CustomCode/FuelEfficiencyTests.cs new file mode 100644 index 0000000000..ccad68f586 --- /dev/null +++ b/UnitsNet.Tests/CustomCode/FuelEfficiencyTests.cs @@ -0,0 +1,32 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.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; + +namespace UnitsNet.Tests.CustomCode +{ + public class FuelEfficiencyTests : FuelEfficiencyTestsBase + { + // Override properties in base class here + protected override double KilometersPerLitersInOneLiterPer100Kilometers => 100; + protected override double LitersPer100KilometersInOneLiterPer100Kilometers => 1; + protected override double MilesPerUkGallonInOneLiterPer100Kilometers => 282.4809363; + protected override double MilesPerUsGallonInOneLiterPer100Kilometers => 235.2145833; + } +} diff --git a/UnitsNet.Tests/GeneratedCode/FuelEfficiencyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/FuelEfficiencyTestsBase.g.cs new file mode 100644 index 0000000000..f66649fa35 --- /dev/null +++ b/UnitsNet.Tests/GeneratedCode/FuelEfficiencyTestsBase.g.cs @@ -0,0 +1,273 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.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.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 FuelEfficiency. + /// +// ReSharper disable once PartialTypeWithSinglePart + public abstract partial class FuelEfficiencyTestsBase + { + protected abstract double KilometersPerLitersInOneLiterPer100Kilometers { get; } + protected abstract double LitersPer100KilometersInOneLiterPer100Kilometers { get; } + protected abstract double MilesPerUkGallonInOneLiterPer100Kilometers { get; } + protected abstract double MilesPerUsGallonInOneLiterPer100Kilometers { get; } + +// ReSharper disable VirtualMemberNeverOverriden.Global + protected virtual double KilometersPerLitersTolerance { get { return 1e-5; } } + protected virtual double LitersPer100KilometersTolerance { get { return 1e-5; } } + protected virtual double MilesPerUkGallonTolerance { get { return 1e-5; } } + protected virtual double MilesPerUsGallonTolerance { get { return 1e-5; } } +// ReSharper restore VirtualMemberNeverOverriden.Global + + [Fact] + public void Ctor_WithUndefinedUnit_ThrowsArgumentException() + { + Assert.Throws(() => new FuelEfficiency((double)0.0, FuelEfficiencyUnit.Undefined)); + } + + [Fact] + public void Ctor_WithInfinityValue_ThrowsArgumentException() + { + Assert.Throws(() => new FuelEfficiency(double.PositiveInfinity, FuelEfficiencyUnit.LiterPer100Kilometers)); + Assert.Throws(() => new FuelEfficiency(double.NegativeInfinity, FuelEfficiencyUnit.LiterPer100Kilometers)); + } + + [Fact] + public void Ctor_WithNaNValue_ThrowsArgumentException() + { + Assert.Throws(() => new FuelEfficiency(double.NaN, FuelEfficiencyUnit.LiterPer100Kilometers)); + } + + [Fact] + public void LiterPer100KilometersToFuelEfficiencyUnits() + { + FuelEfficiency literper100kilometers = FuelEfficiency.FromLitersPer100Kilometers(1); + AssertEx.EqualTolerance(KilometersPerLitersInOneLiterPer100Kilometers, literper100kilometers.KilometersPerLiters, KilometersPerLitersTolerance); + AssertEx.EqualTolerance(LitersPer100KilometersInOneLiterPer100Kilometers, literper100kilometers.LitersPer100Kilometers, LitersPer100KilometersTolerance); + AssertEx.EqualTolerance(MilesPerUkGallonInOneLiterPer100Kilometers, literper100kilometers.MilesPerUkGallon, MilesPerUkGallonTolerance); + AssertEx.EqualTolerance(MilesPerUsGallonInOneLiterPer100Kilometers, literper100kilometers.MilesPerUsGallon, MilesPerUsGallonTolerance); + } + + [Fact] + public void FromValueAndUnit() + { + AssertEx.EqualTolerance(1, FuelEfficiency.From(1, FuelEfficiencyUnit.KilometerPerLiter).KilometersPerLiters, KilometersPerLitersTolerance); + AssertEx.EqualTolerance(1, FuelEfficiency.From(1, FuelEfficiencyUnit.LiterPer100Kilometers).LitersPer100Kilometers, LitersPer100KilometersTolerance); + AssertEx.EqualTolerance(1, FuelEfficiency.From(1, FuelEfficiencyUnit.MilePerUkGallon).MilesPerUkGallon, MilesPerUkGallonTolerance); + AssertEx.EqualTolerance(1, FuelEfficiency.From(1, FuelEfficiencyUnit.MilePerUsGallon).MilesPerUsGallon, MilesPerUsGallonTolerance); + } + + [Fact] + public void FromLitersPer100Kilometers_WithInfinityValue_ThrowsArgumentException() + { + Assert.Throws(() => FuelEfficiency.FromLitersPer100Kilometers(double.PositiveInfinity)); + Assert.Throws(() => FuelEfficiency.FromLitersPer100Kilometers(double.NegativeInfinity)); + } + + [Fact] + public void FromLitersPer100Kilometers_WithNanValue_ThrowsArgumentException() + { + Assert.Throws(() => FuelEfficiency.FromLitersPer100Kilometers(double.NaN)); + } + + [Fact] + public void As() + { + var literper100kilometers = FuelEfficiency.FromLitersPer100Kilometers(1); + AssertEx.EqualTolerance(KilometersPerLitersInOneLiterPer100Kilometers, literper100kilometers.As(FuelEfficiencyUnit.KilometerPerLiter), KilometersPerLitersTolerance); + AssertEx.EqualTolerance(LitersPer100KilometersInOneLiterPer100Kilometers, literper100kilometers.As(FuelEfficiencyUnit.LiterPer100Kilometers), LitersPer100KilometersTolerance); + AssertEx.EqualTolerance(MilesPerUkGallonInOneLiterPer100Kilometers, literper100kilometers.As(FuelEfficiencyUnit.MilePerUkGallon), MilesPerUkGallonTolerance); + AssertEx.EqualTolerance(MilesPerUsGallonInOneLiterPer100Kilometers, literper100kilometers.As(FuelEfficiencyUnit.MilePerUsGallon), MilesPerUsGallonTolerance); + } + + [Fact] + public void ToUnit() + { + var literper100kilometers = FuelEfficiency.FromLitersPer100Kilometers(1); + + var kilometerperliterQuantity = literper100kilometers.ToUnit(FuelEfficiencyUnit.KilometerPerLiter); + AssertEx.EqualTolerance(KilometersPerLitersInOneLiterPer100Kilometers, (double)kilometerperliterQuantity.Value, KilometersPerLitersTolerance); + Assert.Equal(FuelEfficiencyUnit.KilometerPerLiter, kilometerperliterQuantity.Unit); + + var literper100kilometersQuantity = literper100kilometers.ToUnit(FuelEfficiencyUnit.LiterPer100Kilometers); + AssertEx.EqualTolerance(LitersPer100KilometersInOneLiterPer100Kilometers, (double)literper100kilometersQuantity.Value, LitersPer100KilometersTolerance); + Assert.Equal(FuelEfficiencyUnit.LiterPer100Kilometers, literper100kilometersQuantity.Unit); + + var mileperukgallonQuantity = literper100kilometers.ToUnit(FuelEfficiencyUnit.MilePerUkGallon); + AssertEx.EqualTolerance(MilesPerUkGallonInOneLiterPer100Kilometers, (double)mileperukgallonQuantity.Value, MilesPerUkGallonTolerance); + Assert.Equal(FuelEfficiencyUnit.MilePerUkGallon, mileperukgallonQuantity.Unit); + + var mileperusgallonQuantity = literper100kilometers.ToUnit(FuelEfficiencyUnit.MilePerUsGallon); + AssertEx.EqualTolerance(MilesPerUsGallonInOneLiterPer100Kilometers, (double)mileperusgallonQuantity.Value, MilesPerUsGallonTolerance); + Assert.Equal(FuelEfficiencyUnit.MilePerUsGallon, mileperusgallonQuantity.Unit); + } + + [Fact] + public void ConversionRoundTrip() + { + FuelEfficiency literper100kilometers = FuelEfficiency.FromLitersPer100Kilometers(1); + AssertEx.EqualTolerance(1, FuelEfficiency.FromKilometersPerLiters(literper100kilometers.KilometersPerLiters).LitersPer100Kilometers, KilometersPerLitersTolerance); + AssertEx.EqualTolerance(1, FuelEfficiency.FromLitersPer100Kilometers(literper100kilometers.LitersPer100Kilometers).LitersPer100Kilometers, LitersPer100KilometersTolerance); + AssertEx.EqualTolerance(1, FuelEfficiency.FromMilesPerUkGallon(literper100kilometers.MilesPerUkGallon).LitersPer100Kilometers, MilesPerUkGallonTolerance); + AssertEx.EqualTolerance(1, FuelEfficiency.FromMilesPerUsGallon(literper100kilometers.MilesPerUsGallon).LitersPer100Kilometers, MilesPerUsGallonTolerance); + } + + [Fact] + public void ArithmeticOperators() + { + FuelEfficiency v = FuelEfficiency.FromLitersPer100Kilometers(1); + AssertEx.EqualTolerance(-1, -v.LitersPer100Kilometers, LitersPer100KilometersTolerance); + AssertEx.EqualTolerance(2, (FuelEfficiency.FromLitersPer100Kilometers(3)-v).LitersPer100Kilometers, LitersPer100KilometersTolerance); + AssertEx.EqualTolerance(2, (v + v).LitersPer100Kilometers, LitersPer100KilometersTolerance); + AssertEx.EqualTolerance(10, (v*10).LitersPer100Kilometers, LitersPer100KilometersTolerance); + AssertEx.EqualTolerance(10, (10*v).LitersPer100Kilometers, LitersPer100KilometersTolerance); + AssertEx.EqualTolerance(2, (FuelEfficiency.FromLitersPer100Kilometers(10)/5).LitersPer100Kilometers, LitersPer100KilometersTolerance); + AssertEx.EqualTolerance(2, FuelEfficiency.FromLitersPer100Kilometers(10)/FuelEfficiency.FromLitersPer100Kilometers(5), LitersPer100KilometersTolerance); + } + + [Fact] + public void ComparisonOperators() + { + FuelEfficiency oneLiterPer100Kilometers = FuelEfficiency.FromLitersPer100Kilometers(1); + FuelEfficiency twoLitersPer100Kilometers = FuelEfficiency.FromLitersPer100Kilometers(2); + + Assert.True(oneLiterPer100Kilometers < twoLitersPer100Kilometers); + Assert.True(oneLiterPer100Kilometers <= twoLitersPer100Kilometers); + Assert.True(twoLitersPer100Kilometers > oneLiterPer100Kilometers); + Assert.True(twoLitersPer100Kilometers >= oneLiterPer100Kilometers); + + Assert.False(oneLiterPer100Kilometers > twoLitersPer100Kilometers); + Assert.False(oneLiterPer100Kilometers >= twoLitersPer100Kilometers); + Assert.False(twoLitersPer100Kilometers < oneLiterPer100Kilometers); + Assert.False(twoLitersPer100Kilometers <= oneLiterPer100Kilometers); + } + + [Fact] + public void CompareToIsImplemented() + { + FuelEfficiency literper100kilometers = FuelEfficiency.FromLitersPer100Kilometers(1); + Assert.Equal(0, literper100kilometers.CompareTo(literper100kilometers)); + Assert.True(literper100kilometers.CompareTo(FuelEfficiency.Zero) > 0); + Assert.True(FuelEfficiency.Zero.CompareTo(literper100kilometers) < 0); + } + + [Fact] + public void CompareToThrowsOnTypeMismatch() + { + FuelEfficiency literper100kilometers = FuelEfficiency.FromLitersPer100Kilometers(1); + Assert.Throws(() => literper100kilometers.CompareTo(new object())); + } + + [Fact] + public void CompareToThrowsOnNull() + { + FuelEfficiency literper100kilometers = FuelEfficiency.FromLitersPer100Kilometers(1); + Assert.Throws(() => literper100kilometers.CompareTo(null)); + } + + [Fact] + public void EqualityOperators() + { + var a = FuelEfficiency.FromLitersPer100Kilometers(1); + var b = FuelEfficiency.FromLitersPer100Kilometers(2); + + // ReSharper disable EqualExpressionComparison + + Assert.True(a == a); + Assert.False(a != a); + + Assert.True(a != b); + Assert.False(a == b); + + Assert.False(a == null); + Assert.False(null == a); + +// ReSharper restore EqualExpressionComparison + } + + [Fact] + public void EqualsIsImplemented() + { + var a = FuelEfficiency.FromLitersPer100Kilometers(1); + var b = FuelEfficiency.FromLitersPer100Kilometers(2); + + Assert.True(a.Equals(a)); + Assert.False(a.Equals(b)); + Assert.False(a.Equals(null)); + } + + [Fact] + public void EqualsRelativeToleranceIsImplemented() + { + var v = FuelEfficiency.FromLitersPer100Kilometers(1); + Assert.True(v.Equals(FuelEfficiency.FromLitersPer100Kilometers(1), LitersPer100KilometersTolerance, ComparisonType.Relative)); + Assert.False(v.Equals(FuelEfficiency.Zero, LitersPer100KilometersTolerance, ComparisonType.Relative)); + } + + [Fact] + public void EqualsReturnsFalseOnTypeMismatch() + { + FuelEfficiency literper100kilometers = FuelEfficiency.FromLitersPer100Kilometers(1); + Assert.False(literper100kilometers.Equals(new object())); + } + + [Fact] + public void EqualsReturnsFalseOnNull() + { + FuelEfficiency literper100kilometers = FuelEfficiency.FromLitersPer100Kilometers(1); + Assert.False(literper100kilometers.Equals(null)); + } + + [Fact] + public void UnitsDoesNotContainUndefined() + { + Assert.DoesNotContain(FuelEfficiencyUnit.Undefined, FuelEfficiency.Units); + } + + [Fact] + public void HasAtLeastOneAbbreviationSpecified() + { + var units = Enum.GetValues(typeof(FuelEfficiencyUnit)).Cast(); + foreach(var unit in units) + { + if(unit == FuelEfficiencyUnit.Undefined) + continue; + + var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); + } + } + + [Fact] + public void BaseDimensionsShouldNeverBeNull() + { + Assert.False(FuelEfficiency.BaseDimensions is null); + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/FuelEfficiency.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/FuelEfficiency.g.cs new file mode 100644 index 0000000000..89d517c3b3 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/FuelEfficiency.g.cs @@ -0,0 +1,634 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Globalization; +using System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Fuel efficiency is a form of thermal efficiency, meaning the ratio from effort to result of a process that converts chemical potential energy contained in a carrier (fuel) into kinetic energy or work. Fuel economy is stated as "fuel consumption" in liters per 100 kilometers (L/100 km). In countries using non-metric system, fuel economy is expressed in miles per gallon (mpg) (imperial galon or US galon). + /// + /// + /// https://en.wikipedia.org/wiki/Fuel_efficiency + /// + // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components + // Public structures can't have any members other than public fields, and those fields must be value types or strings. + // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. + public sealed partial class FuelEfficiency : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly FuelEfficiencyUnit? _unit; + + static FuelEfficiency() + { + BaseDimensions = BaseDimensions.Dimensionless; + Info = new QuantityInfo(QuantityType.FuelEfficiency, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); + } + + /// + /// Creates the quantity with a value of 0 in the base unit LiterPer100Kilometers. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public FuelEfficiency() + { + _value = 0; + _unit = BaseUnit; + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to 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 FuelEfficiency(double numericValue, FuelEfficiencyUnit unit) + { + if(unit == FuelEfficiencyUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// Information about the quantity type, such as unit values and names. + /// + internal static QuantityInfo Info { get; } + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of FuelEfficiency, which is LiterPer100Kilometers. All conversions go via this value. + /// + public static FuelEfficiencyUnit BaseUnit { get; } = FuelEfficiencyUnit.LiterPer100Kilometers; + + /// + /// Represents the largest possible value of FuelEfficiency + /// + public static FuelEfficiency MaxValue { get; } = new FuelEfficiency(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of FuelEfficiency + /// + public static FuelEfficiency MinValue { get; } = new FuelEfficiency(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType { get; } = QuantityType.FuelEfficiency; + + /// + /// All units of measurement for the FuelEfficiency quantity. + /// + public static FuelEfficiencyUnit[] Units { get; } = Enum.GetValues(typeof(FuelEfficiencyUnit)).Cast().Except(new FuelEfficiencyUnit[]{ FuelEfficiencyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit LiterPer100Kilometers. + /// + public static FuelEfficiency Zero { get; } = new FuelEfficiency(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + object IQuantity.Unit => Unit; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public FuelEfficiencyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + internal QuantityInfo QuantityInfo => Info; + + /// + /// The of this quantity. + /// + public QuantityType Type => FuelEfficiency.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => FuelEfficiency.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get FuelEfficiency in KilometersPerLiters. + /// + public double KilometersPerLiters => As(FuelEfficiencyUnit.KilometerPerLiter); + + /// + /// Get FuelEfficiency in LitersPer100Kilometers. + /// + public double LitersPer100Kilometers => As(FuelEfficiencyUnit.LiterPer100Kilometers); + + /// + /// Get FuelEfficiency in MilesPerUkGallon. + /// + public double MilesPerUkGallon => As(FuelEfficiencyUnit.MilePerUkGallon); + + /// + /// Get FuelEfficiency in MilesPerUsGallon. + /// + public double MilesPerUsGallon => As(FuelEfficiencyUnit.MilePerUsGallon); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(FuelEfficiencyUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(FuelEfficiencyUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get FuelEfficiency from KilometersPerLiters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static FuelEfficiency FromKilometersPerLiters(double kilometersperliters) + { + double value = (double) kilometersperliters; + return new FuelEfficiency(value, FuelEfficiencyUnit.KilometerPerLiter); + } + /// + /// Get FuelEfficiency from LitersPer100Kilometers. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static FuelEfficiency FromLitersPer100Kilometers(double litersper100kilometers) + { + double value = (double) litersper100kilometers; + return new FuelEfficiency(value, FuelEfficiencyUnit.LiterPer100Kilometers); + } + /// + /// Get FuelEfficiency from MilesPerUkGallon. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static FuelEfficiency FromMilesPerUkGallon(double milesperukgallon) + { + double value = (double) milesperukgallon; + return new FuelEfficiency(value, FuelEfficiencyUnit.MilePerUkGallon); + } + /// + /// Get FuelEfficiency from MilesPerUsGallon. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static FuelEfficiency FromMilesPerUsGallon(double milesperusgallon) + { + double value = (double) milesperusgallon; + return new FuelEfficiency(value, FuelEfficiencyUnit.MilePerUsGallon); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// FuelEfficiency unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static FuelEfficiency From(double value, FuelEfficiencyUnit fromUnit) + { + return new FuelEfficiency((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + public static FuelEfficiency Parse(string str) + { + return Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static FuelEfficiency Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out FuelEfficiency result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out FuelEfficiency result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static FuelEfficiencyUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static FuelEfficiencyUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out FuelEfficiencyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out FuelEfficiencyUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Equality / IComparable + + public int CompareTo(object obj) + { + if(obj is null) throw new ArgumentNullException(nameof(obj)); + if(!(obj is FuelEfficiency objFuelEfficiency)) throw new ArgumentException("Expected type FuelEfficiency.", nameof(obj)); + + return CompareTo(objFuelEfficiency); + } + + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + internal int CompareTo(FuelEfficiency other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + [Windows.Foundation.Metadata.DefaultOverload] + public override bool Equals(object obj) + { + if(obj is null || !(obj is FuelEfficiency objFuelEfficiency)) + return false; + + return Equals(objFuelEfficiency); + } + + public bool Equals(FuelEfficiency other) + { + return _value.Equals(other.AsBaseNumericType(this.Unit)); + } + + /// + /// + /// Compare equality to another FuelEfficiency within the given absolute or relative tolerance. + /// + /// + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a percentage of this quantity's value. will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// + /// + /// + /// + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a fixed number in this quantity's unit. will be converted into + /// this quantity's unit for comparison. + /// + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// + /// + /// + /// + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating point operations and using System.Double internally. + /// + /// + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(FuelEfficiency other, double tolerance, ComparisonType comparisonType) + { + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current FuelEfficiency. + public override int GetHashCode() + { + return new { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + double IQuantity.As(object unit) => As((FuelEfficiencyUnit)unit); + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(FuelEfficiencyUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this FuelEfficiency to another FuelEfficiency with the unit representation . + /// + /// A FuelEfficiency with the specified unit. + public FuelEfficiency ToUnit(FuelEfficiencyUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new FuelEfficiency(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case FuelEfficiencyUnit.KilometerPerLiter: return 100/_value; + case FuelEfficiencyUnit.LiterPer100Kilometers: return _value; + case FuelEfficiencyUnit.MilePerUkGallon: return (100*4.54609188)/(1.609344*_value); + case FuelEfficiencyUnit.MilePerUsGallon: return (100*3.785411784)/(1.609344*_value); + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(FuelEfficiencyUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case FuelEfficiencyUnit.KilometerPerLiter: return 100/baseUnitValue; + case FuelEfficiencyUnit.LiterPer100Kilometers: return baseUnitValue; + case FuelEfficiencyUnit.MilePerUkGallon: return (100*4.54609188)/(1.609344*baseUnitValue); + case FuelEfficiencyUnit.MilePerUsGallon: return (100*3.785411784)/(1.609344*baseUnitValue); + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + #endregion + + #region ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantity.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantity.g.cs index ed8d512991..5cb694393a 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantity.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantity.g.cs @@ -155,6 +155,9 @@ internal static bool TryFrom(double value, Enum unit, out IQuantity quantity) case FrequencyUnit frequencyUnit: quantity = Frequency.From(value, frequencyUnit); return true; + case FuelEfficiencyUnit fuelEfficiencyUnit: + quantity = FuelEfficiency.From(value, fuelEfficiencyUnit); + return true; case HeatFluxUnit heatFluxUnit: quantity = HeatFlux.From(value, heatFluxUnit); return true; @@ -496,6 +499,9 @@ internal static bool TryParse([CanBeNull] IFormatProvider formatProvider, Type q if (quantityType == typeof(Frequency)) return parser.TryParse(quantityString, formatProvider, Frequency.From, out quantity); + if (quantityType == typeof(FuelEfficiency)) + return parser.TryParse(quantityString, formatProvider, FuelEfficiency.From, out quantity); + if (quantityType == typeof(HeatFlux)) return parser.TryParse(quantityString, formatProvider, HeatFlux.From, out quantity); diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/QuantityType.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/QuantityType.g.cs index eb1c05724b..11141e7194 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/QuantityType.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/QuantityType.g.cs @@ -67,6 +67,7 @@ public enum QuantityType ForceChangeRate, ForcePerLength, Frequency, + FuelEfficiency, HeatFlux, HeatTransferCoefficient, Illuminance, diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/UnitAbbreviationsCache.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/UnitAbbreviationsCache.g.cs index 8dedebe1b9..5ff08e9881 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/UnitAbbreviationsCache.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/UnitAbbreviationsCache.g.cs @@ -407,6 +407,10 @@ private static readonly (string CultureName, Type UnitType, int UnitValue, strin ("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(FuelEfficiencyUnit), (int)FuelEfficiencyUnit.KilometerPerLiter, new string[]{"km/l"}), + ("en-US", typeof(FuelEfficiencyUnit), (int)FuelEfficiencyUnit.LiterPer100Kilometers, new string[]{"l/100km"}), + ("en-US", typeof(FuelEfficiencyUnit), (int)FuelEfficiencyUnit.MilePerUkGallon, new string[]{"mpg (imp)"}), + ("en-US", typeof(FuelEfficiencyUnit), (int)FuelEfficiencyUnit.MilePerUsGallon, new string[]{"mpg (US)"}), ("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²"}), diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/FuelEfficiencyUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/FuelEfficiencyUnit.g.cs new file mode 100644 index 0000000000..92f981c2a2 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/FuelEfficiencyUnit.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. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum FuelEfficiencyUnit + { + Undefined = 0, + KilometerPerLiter, + LiterPer100Kilometers, + MilePerUkGallon, + MilePerUsGallon, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs b/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs new file mode 100644 index 0000000000..d7beaef9e6 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs @@ -0,0 +1,904 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Globalization; +using System.Linq; +using JetBrains.Annotations; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// + /// Fuel efficiency is a form of thermal efficiency, meaning the ratio from effort to result of a process that converts chemical potential energy contained in a carrier (fuel) into kinetic energy or work. Fuel economy is stated as "fuel consumption" in liters per 100 kilometers (L/100 km). In countries using non-metric system, fuel economy is expressed in miles per gallon (mpg) (imperial galon or US galon). + /// + /// + /// https://en.wikipedia.org/wiki/Fuel_efficiency + /// + public partial struct FuelEfficiency : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly FuelEfficiencyUnit? _unit; + + static FuelEfficiency() + { + BaseDimensions = BaseDimensions.Dimensionless; + + Info = new QuantityInfo(QuantityType.FuelEfficiency, + new UnitInfo[] { + new UnitInfo(FuelEfficiencyUnit.KilometerPerLiter, BaseUnits.Undefined), + new UnitInfo(FuelEfficiencyUnit.LiterPer100Kilometers, BaseUnits.Undefined), + new UnitInfo(FuelEfficiencyUnit.MilePerUkGallon, BaseUnits.Undefined), + new UnitInfo(FuelEfficiencyUnit.MilePerUsGallon, BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// If value is NaN or Infinity. + public FuelEfficiency(double numericValue, FuelEfficiencyUnit unit) + { + if(unit == FuelEfficiencyUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _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 contruct this quantity with. + /// The unit system to create the quantity with. + /// The given is null. + /// No unit was found for the given . + public FuelEfficiency(double numericValue, UnitSystem unitSystem) + { + if(unitSystem == null) throw new ArgumentNullException(nameof(unitSystem)); + + var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); + var firstUnitInfo = unitInfos.FirstOrDefault(); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); + } + + #region Static Properties + + /// + public static QuantityInfo Info { get; } + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of FuelEfficiency, which is LiterPer100Kilometers. All conversions go via this value. + /// + public static FuelEfficiencyUnit BaseUnit { get; } = FuelEfficiencyUnit.LiterPer100Kilometers; + + /// + /// Represents the largest possible value of FuelEfficiency + /// + public static FuelEfficiency MaxValue { get; } = new FuelEfficiency(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of FuelEfficiency + /// + public static FuelEfficiency MinValue { get; } = new FuelEfficiency(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType { get; } = QuantityType.FuelEfficiency; + + /// + /// All units of measurement for the FuelEfficiency quantity. + /// + public static FuelEfficiencyUnit[] Units { get; } = Enum.GetValues(typeof(FuelEfficiencyUnit)).Cast().Except(new FuelEfficiencyUnit[]{ FuelEfficiencyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit LiterPer100Kilometers. + /// + public static FuelEfficiency Zero { get; } = new FuelEfficiency(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + Enum IQuantity.Unit => Unit; + + /// + public FuelEfficiencyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + public QuantityInfo QuantityInfo => Info; + + /// + QuantityInfo IQuantity.QuantityInfo => Info; + + /// + /// The of this quantity. + /// + public QuantityType Type => FuelEfficiency.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => FuelEfficiency.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get FuelEfficiency in KilometersPerLiters. + /// + public double KilometersPerLiters => As(FuelEfficiencyUnit.KilometerPerLiter); + + /// + /// Get FuelEfficiency in LitersPer100Kilometers. + /// + public double LitersPer100Kilometers => As(FuelEfficiencyUnit.LiterPer100Kilometers); + + /// + /// Get FuelEfficiency in MilesPerUkGallon. + /// + public double MilesPerUkGallon => As(FuelEfficiencyUnit.MilePerUkGallon); + + /// + /// Get FuelEfficiency in MilesPerUsGallon. + /// + public double MilesPerUsGallon => As(FuelEfficiencyUnit.MilePerUsGallon); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(FuelEfficiencyUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(FuelEfficiencyUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get FuelEfficiency from KilometersPerLiters. + /// + /// If value is NaN or Infinity. + public static FuelEfficiency FromKilometersPerLiters(QuantityValue kilometersperliters) + { + double value = (double) kilometersperliters; + return new FuelEfficiency(value, FuelEfficiencyUnit.KilometerPerLiter); + } + /// + /// Get FuelEfficiency from LitersPer100Kilometers. + /// + /// If value is NaN or Infinity. + public static FuelEfficiency FromLitersPer100Kilometers(QuantityValue litersper100kilometers) + { + double value = (double) litersper100kilometers; + return new FuelEfficiency(value, FuelEfficiencyUnit.LiterPer100Kilometers); + } + /// + /// Get FuelEfficiency from MilesPerUkGallon. + /// + /// If value is NaN or Infinity. + public static FuelEfficiency FromMilesPerUkGallon(QuantityValue milesperukgallon) + { + double value = (double) milesperukgallon; + return new FuelEfficiency(value, FuelEfficiencyUnit.MilePerUkGallon); + } + /// + /// Get FuelEfficiency from MilesPerUsGallon. + /// + /// If value is NaN or Infinity. + public static FuelEfficiency FromMilesPerUsGallon(QuantityValue milesperusgallon) + { + double value = (double) milesperusgallon; + return new FuelEfficiency(value, FuelEfficiencyUnit.MilePerUsGallon); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// FuelEfficiency unit value. + public static FuelEfficiency From(QuantityValue value, FuelEfficiencyUnit fromUnit) + { + return new FuelEfficiency((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + public static FuelEfficiency Parse(string str) + { + return Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static FuelEfficiency 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 FuelEfficiency result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out FuelEfficiency 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 FuelEfficiencyUnit 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", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static FuelEfficiencyUnit ParseUnit(string str, [CanBeNull] IFormatProvider provider) + { + return UnitParser.Default.Parse(str, provider); + } + + /// + public static bool TryParseUnit(string str, out FuelEfficiencyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out FuelEfficiencyUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// Negate the value. + public static FuelEfficiency operator -(FuelEfficiency right) + { + return new FuelEfficiency(-right.Value, right.Unit); + } + + /// Get from adding two . + public static FuelEfficiency operator +(FuelEfficiency left, FuelEfficiency right) + { + return new FuelEfficiency(left.Value + right.GetValueAs(left.Unit), left.Unit); + } + + /// Get from subtracting two . + public static FuelEfficiency operator -(FuelEfficiency left, FuelEfficiency right) + { + return new FuelEfficiency(left.Value - right.GetValueAs(left.Unit), left.Unit); + } + + /// Get from multiplying value and . + public static FuelEfficiency operator *(double left, FuelEfficiency right) + { + return new FuelEfficiency(left * right.Value, right.Unit); + } + + /// Get from multiplying value and . + public static FuelEfficiency operator *(FuelEfficiency left, double right) + { + return new FuelEfficiency(left.Value * right, left.Unit); + } + + /// Get from dividing by value. + public static FuelEfficiency operator /(FuelEfficiency left, double right) + { + return new FuelEfficiency(left.Value / right, left.Unit); + } + + /// Get ratio value from dividing by . + public static double operator /(FuelEfficiency left, FuelEfficiency right) + { + return left.LitersPer100Kilometers / right.LitersPer100Kilometers; + } + + #endregion + + #region Equality / IComparable + + /// Returns true if less or equal to. + public static bool operator <=(FuelEfficiency left, FuelEfficiency right) + { + return left.Value <= right.GetValueAs(left.Unit); + } + + /// Returns true if greater than or equal to. + public static bool operator >=(FuelEfficiency left, FuelEfficiency right) + { + return left.Value >= right.GetValueAs(left.Unit); + } + + /// Returns true if less than. + public static bool operator <(FuelEfficiency left, FuelEfficiency right) + { + return left.Value < right.GetValueAs(left.Unit); + } + + /// Returns true if greater than. + public static bool operator >(FuelEfficiency left, FuelEfficiency right) + { + return left.Value > right.GetValueAs(left.Unit); + } + + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(FuelEfficiency left, FuelEfficiency right) + { + return left.Equals(right); + } + + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(FuelEfficiency left, FuelEfficiency right) + { + return !(left == right); + } + + /// + public int CompareTo(object obj) + { + if(obj is null) throw new ArgumentNullException(nameof(obj)); + if(!(obj is FuelEfficiency objFuelEfficiency)) throw new ArgumentException("Expected type FuelEfficiency.", nameof(obj)); + + return CompareTo(objFuelEfficiency); + } + + /// + public int CompareTo(FuelEfficiency other) + { + return _value.CompareTo(other.GetValueAs(this.Unit)); + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if(obj is null || !(obj is FuelEfficiency objFuelEfficiency)) + return false; + + return Equals(objFuelEfficiency); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(FuelEfficiency other) + { + return _value.Equals(other.GetValueAs(this.Unit)); + } + + /// + /// + /// Compare equality to another FuelEfficiency within the given absolute or relative tolerance. + /// + /// + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a percentage of this quantity's value. will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// + /// + /// + /// + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a fixed number in this quantity's unit. will be converted into + /// this quantity's unit for comparison. + /// + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// + /// + /// + /// + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating point operations and using System.Double internally. + /// + /// + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(FuelEfficiency other, double tolerance, ComparisonType comparisonType) + { + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current FuelEfficiency. + public override int GetHashCode() + { + return new { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(FuelEfficiencyUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = GetValueAs(unit); + return Convert.ToDouble(converted); + } + + /// + public double As(UnitSystem unitSystem) + { + if(unitSystem == 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 FuelEfficiencyUnit unitAsFuelEfficiencyUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FuelEfficiencyUnit)} is supported.", nameof(unit)); + + return As(unitAsFuelEfficiencyUnit); + } + + /// + /// Converts this FuelEfficiency to another FuelEfficiency with the unit representation . + /// + /// A FuelEfficiency with the specified unit. + public FuelEfficiency ToUnit(FuelEfficiencyUnit unit) + { + var convertedValue = GetValueAs(unit); + return new FuelEfficiency(convertedValue, unit); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit) + { + if(!(unit is FuelEfficiencyUnit unitAsFuelEfficiencyUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FuelEfficiencyUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsFuelEfficiencyUnit); + } + + /// + public FuelEfficiency ToUnit(UnitSystem unitSystem) + { + if(unitSystem == 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(FuelEfficiencyUnit unit) => ToUnit(unit); + + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + + /// + /// Converts the current value + unit to the 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() + { + switch(Unit) + { + case FuelEfficiencyUnit.KilometerPerLiter: return 100/_value; + case FuelEfficiencyUnit.LiterPer100Kilometers: return _value; + case FuelEfficiencyUnit.MilePerUkGallon: return (100*4.54609188)/(1.609344*_value); + case FuelEfficiencyUnit.MilePerUsGallon: return (100*3.785411784)/(1.609344*_value); + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + internal FuelEfficiency ToBaseUnit() + { + var baseUnitValue = GetValueInBaseUnit(); + return new FuelEfficiency(baseUnitValue, BaseUnit); + } + + private double GetValueAs(FuelEfficiencyUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + switch(unit) + { + case FuelEfficiencyUnit.KilometerPerLiter: return 100/baseUnitValue; + case FuelEfficiencyUnit.LiterPer100Kilometers: return baseUnitValue; + case FuelEfficiencyUnit.MilePerUkGallon: return (100*4.54609188)/(1.609344*baseUnitValue); + case FuelEfficiencyUnit.MilePerUsGallon: return (100*3.785411784)/(1.609344*baseUnitValue); + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + #endregion + + #region ToString Methods + + /// + /// 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([CanBeNull] IFormatProvider provider) + { + return ToString("g", provider); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] + 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 ?? CultureInfo.CurrentUICulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + /// + /// + /// Gets the string representation of this instance in the specified format string using . + /// + /// The format string. + /// The string representation. + public string ToString(string format) + { + return ToString(format, CultureInfo.CurrentUICulture); + } + + /// + /// + /// 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 formatProvider) + { + return QuantityFormatter.Format(this, format, formatProvider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider provider) + { + throw new InvalidCastException($"Converting {typeof(FuelEfficiency)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider provider) + { + throw new InvalidCastException($"Converting {typeof(FuelEfficiency)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider provider) + { + throw new InvalidCastException($"Converting {typeof(FuelEfficiency)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider provider) + { + if(conversionType == typeof(FuelEfficiency)) + return this; + else if(conversionType == typeof(FuelEfficiencyUnit)) + return Unit; + else if(conversionType == typeof(QuantityType)) + return FuelEfficiency.QuantityType; + else if(conversionType == typeof(BaseDimensions)) + return FuelEfficiency.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(FuelEfficiency)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet/GeneratedCode/Quantity.g.cs b/UnitsNet/GeneratedCode/Quantity.g.cs index 8ad605eb01..cc8d944318 100644 --- a/UnitsNet/GeneratedCode/Quantity.g.cs +++ b/UnitsNet/GeneratedCode/Quantity.g.cs @@ -116,6 +116,8 @@ public static IQuantity FromQuantityType(QuantityType quantityType, QuantityValu return ForcePerLength.From(value, ForcePerLength.BaseUnit); case QuantityType.Frequency: return Frequency.From(value, Frequency.BaseUnit); + case QuantityType.FuelEfficiency: + return FuelEfficiency.From(value, FuelEfficiency.BaseUnit); case QuantityType.HeatFlux: return HeatFlux.From(value, HeatFlux.BaseUnit); case QuantityType.HeatTransferCoefficient: @@ -364,6 +366,9 @@ public static bool TryFrom(QuantityValue value, Enum unit, out IQuantity quantit case FrequencyUnit frequencyUnit: quantity = Frequency.From(value, frequencyUnit); return true; + case FuelEfficiencyUnit fuelEfficiencyUnit: + quantity = FuelEfficiency.From(value, fuelEfficiencyUnit); + return true; case HeatFluxUnit heatFluxUnit: quantity = HeatFlux.From(value, heatFluxUnit); return true; @@ -644,6 +649,8 @@ public static bool TryParse([CanBeNull] IFormatProvider formatProvider, Type qua return parser.TryParse(quantityString, formatProvider, ForcePerLength.From, out quantity); case Type _ when quantityType == typeof(Frequency): return parser.TryParse(quantityString, formatProvider, Frequency.From, out quantity); + case Type _ when quantityType == typeof(FuelEfficiency): + return parser.TryParse(quantityString, formatProvider, FuelEfficiency.From, out quantity); case Type _ when quantityType == typeof(HeatFlux): return parser.TryParse(quantityString, formatProvider, HeatFlux.From, out quantity); case Type _ when quantityType == typeof(HeatTransferCoefficient): diff --git a/UnitsNet/GeneratedCode/QuantityType.g.cs b/UnitsNet/GeneratedCode/QuantityType.g.cs index 4c71b1ac40..2cd7a9da29 100644 --- a/UnitsNet/GeneratedCode/QuantityType.g.cs +++ b/UnitsNet/GeneratedCode/QuantityType.g.cs @@ -69,6 +69,7 @@ public enum QuantityType ForceChangeRate, ForcePerLength, Frequency, + FuelEfficiency, HeatFlux, HeatTransferCoefficient, Illuminance, diff --git a/UnitsNet/GeneratedCode/UnitAbbreviationsCache.g.cs b/UnitsNet/GeneratedCode/UnitAbbreviationsCache.g.cs index 1eb2e42817..275d7c768b 100644 --- a/UnitsNet/GeneratedCode/UnitAbbreviationsCache.g.cs +++ b/UnitsNet/GeneratedCode/UnitAbbreviationsCache.g.cs @@ -407,6 +407,10 @@ private static readonly (string CultureName, Type UnitType, int UnitValue, strin ("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(FuelEfficiencyUnit), (int)FuelEfficiencyUnit.KilometerPerLiter, new string[]{"km/l"}), + ("en-US", typeof(FuelEfficiencyUnit), (int)FuelEfficiencyUnit.LiterPer100Kilometers, new string[]{"l/100km"}), + ("en-US", typeof(FuelEfficiencyUnit), (int)FuelEfficiencyUnit.MilePerUkGallon, new string[]{"mpg (imp)"}), + ("en-US", typeof(FuelEfficiencyUnit), (int)FuelEfficiencyUnit.MilePerUsGallon, new string[]{"mpg (US)"}), ("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²"}), diff --git a/UnitsNet/GeneratedCode/UnitConverter.g.cs b/UnitsNet/GeneratedCode/UnitConverter.g.cs index ab9d15535e..69e9c87948 100644 --- a/UnitsNet/GeneratedCode/UnitConverter.g.cs +++ b/UnitsNet/GeneratedCode/UnitConverter.g.cs @@ -620,6 +620,13 @@ public static void RegisterDefaultConversions(UnitConverter unitConverter) unitConverter.SetConversionFunction(FrequencyUnit.RadianPerSecond, Frequency.BaseUnit, q => q.ToBaseUnit()); unitConverter.SetConversionFunction(Frequency.BaseUnit, FrequencyUnit.Terahertz, q => q.ToUnit(FrequencyUnit.Terahertz)); unitConverter.SetConversionFunction(FrequencyUnit.Terahertz, Frequency.BaseUnit, q => q.ToBaseUnit()); + unitConverter.SetConversionFunction(FuelEfficiency.BaseUnit, FuelEfficiencyUnit.KilometerPerLiter, q => q.ToUnit(FuelEfficiencyUnit.KilometerPerLiter)); + unitConverter.SetConversionFunction(FuelEfficiencyUnit.KilometerPerLiter, FuelEfficiency.BaseUnit, q => q.ToBaseUnit()); + unitConverter.SetConversionFunction(FuelEfficiency.BaseUnit, FuelEfficiency.BaseUnit, q => q); + unitConverter.SetConversionFunction(FuelEfficiency.BaseUnit, FuelEfficiencyUnit.MilePerUkGallon, q => q.ToUnit(FuelEfficiencyUnit.MilePerUkGallon)); + unitConverter.SetConversionFunction(FuelEfficiencyUnit.MilePerUkGallon, FuelEfficiency.BaseUnit, q => q.ToBaseUnit()); + unitConverter.SetConversionFunction(FuelEfficiency.BaseUnit, FuelEfficiencyUnit.MilePerUsGallon, q => q.ToUnit(FuelEfficiencyUnit.MilePerUsGallon)); + unitConverter.SetConversionFunction(FuelEfficiencyUnit.MilePerUsGallon, FuelEfficiency.BaseUnit, q => q.ToBaseUnit()); unitConverter.SetConversionFunction(HeatFlux.BaseUnit, HeatFluxUnit.BtuPerHourSquareFoot, q => q.ToUnit(HeatFluxUnit.BtuPerHourSquareFoot)); unitConverter.SetConversionFunction(HeatFluxUnit.BtuPerHourSquareFoot, HeatFlux.BaseUnit, q => q.ToBaseUnit()); unitConverter.SetConversionFunction(HeatFlux.BaseUnit, HeatFluxUnit.BtuPerMinuteSquareFoot, q => q.ToUnit(HeatFluxUnit.BtuPerMinuteSquareFoot)); diff --git a/UnitsNet/GeneratedCode/Units/FuelEfficiencyUnit.g.cs b/UnitsNet/GeneratedCode/Units/FuelEfficiencyUnit.g.cs new file mode 100644 index 0000000000..92f981c2a2 --- /dev/null +++ b/UnitsNet/GeneratedCode/Units/FuelEfficiencyUnit.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. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum FuelEfficiencyUnit + { + Undefined = 0, + KilometerPerLiter, + LiterPer100Kilometers, + MilePerUkGallon, + MilePerUsGallon, + } + + #pragma warning restore 1591 +}