Skip to content

Math.Clamp ArgumentException uses SR.Argument_MinMaxValue differently than Random.Next() #115337

Open
@pangeorg

Description

@pangeorg

Summary

Using Math.Clamp when min > max will result in an ArgumentException stating:
'System.ArgumentException: '0' cannot be greater than -2', which is somewhat weird to read.

Random.Next uses a different approach when using a min value larger than max:
'System.ArgumentOutOfRangeException: 'minValue' cannot be greater than maxValue. (Parameter 'minValue')'

Minimal reproduction Code:

// Clamp behavior:
try
{
    Math.Clamp(10, 0, -2);
}
catch (ArgumentException e)
{
    Console.WriteLine(e);
    // writes: System.ArgumentException: '0' cannot be greater than -2.
}

// random behavior
try
{
    var r = new Random();
    r.Next(2, 1);
}
catch (ArgumentOutOfRangeException e)
{
    Console.WriteLine(e);
    //writs: System.ArgumentOutOfRangeException: 'minValue' cannot be greater than maxValue. (Parameter 'minValue')
}

Proposal

I guess the Random.Next handling is the intended behavior? I can take the task and change the respective place in Math.cs

throw new ArgumentException(SR.Format(SR.Argument_MinMaxValue, min, max));

to what is used in Random

throw new ArgumentOutOfRangeException("minValue", SR.Format(SR.Argument_MinMaxValue, "minValue", "maxValue"));

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions