Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ Experiment with Generic Math in .NET6 #984

Closed
wants to merge 2 commits into from
Closed

Conversation

angularsen
Copy link
Owner

@angularsen angularsen commented Nov 2, 2021

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

@stale
Copy link

stale bot commented Jan 3, 2022

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 stale bot added the wontfix label Jan 3, 2022
@tmilnthorp
Copy link
Collaborator

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

@stale stale bot removed the wontfix label Jan 26, 2022
@angularsen angularsen added the pinned Issues that should not be auto-closed due to inactivity. label Jan 26, 2022
@tmilnthorp tmilnthorp mentioned this pull request Jan 31, 2022
@angularsen
Copy link
Owner Author

Merged by #1164

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
pinned Issues that should not be auto-closed due to inactivity.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants