Skip to content

Add generic overloads to Math.Min and Math.Max #14510

@svick

Description

@svick

There are overloads of Math.Min and Math.Max for all the numeric types, but there aren't any for general comparable types (including framework types like DateTime and TimeSpan). It would be nice to have them.

Rationale

For integral types, Math.Min and Math.Max are not necessary, e.g. instead of Math.Min(a, b), you can write a <= b ? a : b. But they are nice, because they make the meaning clear and decrease the likelihood of error. The same argument applies to general comparable types, so they should work with Math.Min and Math.Max too.

Proposed API

public static class Math
{
    public static T Min<T>(T val1, T val2) where T : IComparable<T>;
    public static T Min<T>(T val1, T val2, IComparer<T> comparer);

    public static T Max<T>(T val1, T val2) where T : IComparable<T>;
    public static T Max<T>(T val1, T val2, IComparer<T> comparer);
}

Open questions

  • Should the constraint where T : IComparable<T> be there? Other framework methods that require comparison, like Enumerable.OrderBy, don't have it and instead use Comparer<T>.Default.
  • Should nullable value types be supported? The proposed version doesn't, because T? does not implement IComparable<T?>, even when T does implement IComparable<T>.

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-needs-workAPI needs work before it is approved, it is NOT ready for implementationarea-System.Runtimehelp wanted[up-for-grabs] Good issue for external contributors

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions