How to force a number to be in a range in C#? [duplicate]

This operation is called ‘Clamp’ and it’s usually written like this:

public static int Clamp( int value, int min, int max )
{
    return (value < min) ? min : (value > max) ? max : value;
}

Leave a Comment