Skip to content

Add multi-parameter overloads for Math.Max and Math.Min #24737

@cshaa

Description

@cshaa

It would be logical if Math.Max and Math.Min had overloads for three, four and more parameters. I don't see why don't we have them already. They would be very easy to implement and backwards compatible.

Rationale

When you need a method to take three non-negative ints you have to do one of the following:

  • something like Math.Min(Math.Min(a,b),c) < 0, which is really ugly and unreadable
  • take uints and cast them (which often results in double-casting because you have an int, you cast it to uint to pass it to the method and it casts it back to int again)
  • check for every parameter separately, which is not very elegant
  • define your own Min method – this is the best solution but because you can't extend static classes, you'll end up with something awkward like MathExtensions.Min(a,b,c)
    But if we had the overloads, we could simply do Math.Min(a,b,c)

Proposed API

I'll use a kind of pseudo-code. In actual implementation the number would have to be replaced by int, long, float, double, ...

public static class Math
{
    public static number Max(number a, number b, number c);
    public static number Max(number a, number b, number c, number d);
    public static number Max(params number[] list);
    
    public static number Min(number a, number b, number c);
    public static number Min(number a, number b, number c, number d);
    public static number Min(params number[] list);
}

Moved from dotnet/csharplang#1263.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions