Is there an elegant way to determine if number is between a min and a max value and if not set the min/max value? Useful when you add/subtract but you don't want to go below zero and above a limit.
There are some clear solutions to this but it seems like a crucial function and I'd thought there should be something more clean and elegant than using two if's or two ternary operators. Of course one can always create his own method but why reinvent the wheel.
Here's what I mean:
int limit(int lowerBound, int upperBound, int number)
{
return (number < lowerBound) ? lowerBound : (number > upperBound) ? upperBound : number;
}
int limit2(int lowerBound, int upperBound, int number)
{
if (number < lowerBound)
{
return lowerBound;
}
else if (number > upperBound)
{
return upperBound;
}
else
{
return number;
}
}
[EDIT]
Sorry, didn't realize the word clamp, so I didn't find it was already asked once. But anyway, this one-liner is great, although its purpose may not be obvious at first sight, but it suffices my needs perfectly. Thanks to whoever posted it (but then deleted their answer).
int foo = Math.Max(Math.Min(upperBound, number), lowerBound);