UnitsNet icon indicating copy to clipboard operation
UnitsNet copied to clipboard

✨ Experiment with Generic Math in .NET6

Open angularsen opened this issue 4 years ago • 2 comments

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

angularsen avatar Nov 02 '21 21:11 angularsen

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.

stale[bot] avatar Jan 03 '22 21:01 stale[bot]

Love it. It doesn't seem like there is a way to make it backwards compatible to netstandard, etc. though :(

tmilnthorp avatar Jan 26 '22 21:01 tmilnthorp

Merged by #1164

angularsen avatar Dec 29 '22 16:12 angularsen