UnitsNet
UnitsNet copied to clipboard
✨ Experiment with Generic Math in .NET6
Experimenting with https://devblogs.microsoft.com/dotnet/preview-features-in-net-6-generic-math/
Example:
public interface IQuantity<TQuantity> :
IAdditionOperators<TQuantity, TQuantity, TQuantity>,
IParseable<TQuantity>,
IComparisonOperators<TQuantity, TQuantity>,
IAdditiveIdentity<TQuantity, TQuantity>
where TQuantity : IQuantity<TQuantity>
{
static abstract TQuantity Zero { get; }
}
Allows us to do:
void Foo<TQuantity>(TQuantity left, TQuantity right)
where TQuantity : IQuantity<TQuantity>
{
WriteLine(left.CompareTo(right));
WriteLine(left + right);
WriteLine(TQuantity.Parse("25 m", null);
}
TQuantity Sum<TQuantity>(IEnumerable<TQuantity> items)
where TQuantity : IQuantity<TQuantity>
{
return items.Aggregate(TQuantity.Zero, (acc, item) => acc + item);
}
Full sample output:
Foo(1 Meter, 10 Centimeter)
---
1 <== left.CompareTo(right)
1.1 Meter <== left + right
25 Meter <== TQuantity.Parse("25 m", null)
10 Meter <== Sum [1,2,3,4] array of meters
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
Love it. It doesn't seem like there is a way to make it backwards compatible to netstandard, etc. though :(
Merged by #1164