A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/angularsen/UnitsNet/wiki/Extending-with-Custom-Units below:

Extending with Custom Units · angularsen/UnitsNet Wiki · GitHub

This article is for when you want to add your own custom quantities and units at runtime, not included in the UnitsNet nuget.

To add new quantities or units to the UnitsNet nuget, please see https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit.

⚠️ Disclaimer: This is highly experimental and incomplete

You miss out on the statically generated code for members like Length.FromMeters(1) and myLength.Meters.
Conversion methods like myLength.As() and myLength.ToUnit() currently only support their respective unit enums, in this case LengthUnit.

Can I add a custom unit to an existing quantity in UnitsNet?

Currently, no.

You can only add new custom quantities with their own units and you can only add it at runtime. No code generation.

See example quantity HowMuch below.

Since UnitsNet is so statically typed, your options are limited to:

  1. Submit a pull request to add a new unit to the UnitsNet nuget
  2. Build your own custom version of UnitsNet
Why add a custom quantity?

Good question.

In its current state, the support for custom quantities and units is limited and provides limited integration with the existing units and code. We consider it exploratory, to see what is possible, and we welcome ideas on how it can be improved.

Got more ideas? Create a discussion or issue.

Units.NET roughly consists of these parts:

Example: Custom quantity HowMuch with units HowMuchUnit
GetDefaultAbbreviation(): sm, lts, tns
Parse<HowMuchUnit>(): Some, Lots, Tons

Convert 10 tons to:
200 sm
100 lts
10 tns
Map unit enum values to unit abbreviations
UnitAbbreviationsCache.Default.MapUnitToDefaultAbbreviation(HowMuchUnit.Some, "sm");
UnitAbbreviationsCache.Default.MapUnitToDefaultAbbreviation(HowMuchUnit.Lots, "lts");
UnitAbbreviationsCache.Default.MapUnitToDefaultAbbreviation(HowMuchUnit.Tons, "tns");
Lookup unit abbrevations from enum values
Console.WriteLine("GetDefaultAbbreviation(): " + string.Join(", ", 
	UnitAbbreviationsCache.Default.GetDefaultAbbreviation(HowMuchUnit.Some), // "sm"
	UnitAbbreviationsCache.Default.GetDefaultAbbreviation(HowMuchUnit.Lots), // "lts"
	UnitAbbreviationsCache.Default.GetDefaultAbbreviation(HowMuchUnit.Tons)	 // "tns"
));
Parse unit abbreviations back to enum values
Console.WriteLine("Parse<HowMuchUnit>(): " + string.Join(", ",
	UnitParser.Default.Parse<HowMuchUnit>("sm"),  // Some
	UnitParser.Default.Parse<HowMuchUnit>("lts"), // Lots
	UnitParser.Default.Parse<HowMuchUnit>("tns")  // Tons
));
Convert between units of custom quantity
var unitConverter = UnitConverter.Default;
unitConverter.SetConversionFunction<HowMuch>(HowMuchUnit.Lots, HowMuchUnit.Some, x => new HowMuch(x.Value * 2, HowMuchUnit.Some));
unitConverter.SetConversionFunction<HowMuch>(HowMuchUnit.Tons, HowMuchUnit.Lots, x => new HowMuch(x.Value * 10, HowMuchUnit.Lots));
unitConverter.SetConversionFunction<HowMuch>(HowMuchUnit.Tons, HowMuchUnit.Some, x => new HowMuch(x.Value * 20, HowMuchUnit.Some));

var from = new HowMuch(10, HowMuchUnit.Tons);
IQuantity Convert(HowMuchUnit toUnit) => unitConverter.GetConversionFunction<HowMuch>(from.Unit, toUnit)(from);

Console.WriteLine($"Convert 10 tons to:");
Console.WriteLine(Convert(HowMuchUnit.Some)); // 200 sm
Console.WriteLine(Convert(HowMuchUnit.Lots)); // 100 lts
Console.WriteLine(Convert(HowMuchUnit.Tons)); // 10 tns

https://github.com/angularsen/UnitsNet/blob/master/UnitsNet.Tests/CustomQuantities/HowMuchUnit.cs
https://github.com/angularsen/UnitsNet/blob/master/UnitsNet.Tests/CustomQuantities/HowMuch.cs

public enum HowMuchUnit
{
	Some,
	Lots,
	Tons
}

public struct HowMuch : IQuantity
{
	public HowMuch(double value, HowMuchUnit unit)
	{
		Unit = unit;
		Value = value;
	}

	Enum IQuantity.Unit => Unit;
	public HowMuchUnit Unit { get; }

	public double Value { get; }

	#region IQuantity

	private static readonly HowMuch Zero = new HowMuch(0, HowMuchUnit.Some);

	public QuantityType Type => QuantityType.Undefined;
	public BaseDimensions Dimensions => BaseDimensions.Dimensionless;

	public QuantityInfo QuantityInfo => new QuantityInfo(Type,
		new UnitInfo[]
		{
				new UnitInfo<HowMuchUnit>(HowMuchUnit.Some, BaseUnits.Undefined),
				new UnitInfo<HowMuchUnit>(HowMuchUnit.Lots, BaseUnits.Undefined),
				new UnitInfo<HowMuchUnit>(HowMuchUnit.Tons, BaseUnits.Undefined),
		},
		HowMuchUnit.Some,
		Zero,
		BaseDimensions.Dimensionless);

	public double As(Enum unit) => Convert.ToDouble(unit);

	public double As(UnitSystem unitSystem) => throw new NotImplementedException();

	public IQuantity ToUnit(Enum unit)
	{
		if (unit is HowMuchUnit howMuchUnit) return new HowMuch(As(unit), howMuchUnit);
		throw new ArgumentException("Must be of type HowMuchUnit.", nameof(unit));
	}

	public IQuantity ToUnit(UnitSystem unitSystem) => throw new NotImplementedException();

	public override string ToString() => $"{Value} {UnitAbbreviationsCache.Default.GetDefaultAbbreviation(Unit)}";
	public string ToString(string format, IFormatProvider formatProvider) => $"HowMuch ({format}, {formatProvider})";
	public string ToString(IFormatProvider provider) => $"HowMuch ({provider})";
	public string ToString(IFormatProvider provider, int significantDigitsAfterRadix) => $"HowMuch ({provider}, {significantDigitsAfterRadix})";
	public string ToString(IFormatProvider provider, string format, params object[] args) => $"HowMuch ({provider}, {string.Join(", ", args)})";

	#endregion
}

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4