In C#, I often have to limit an integer value to a range of values. For example, if an application expects a percentage, an integer from a user input must not be less than zero or more than one hundred. Another example: if there are five web pages which are accessed through Request.Params["p"]
, I expect a value from 1 to 5, not 0 or 256 or 99999.
I often end by writing a quite ugly code like:
page = Math.Max(0, Math.Min(2, page));
or even uglier:
percentage = (inputPercentage < 0 || inputPercentage > 100) ? 0 : inputPercentage;
Isn't there a smarter way to do such things within .NET Framework?
I know I can write a general method int LimitToRange(int value, int inclusiveMinimum, int inlusiveMaximum)
and use it in every project, but maybe there is already a magic method in the framework?
If I need to do it manually, what would be the "best" (ie. less uglier and more fast) way to do what I'm doing in the first example? Something like this?
public int LimitToRange(int value, int inclusiveMinimum, int inlusiveMaximum) { if (value >= inclusiveMinimum) { if (value <= inlusiveMaximum) { return value; } return inlusiveMaximum; } return inclusiveMinimum; }
Using range in switch case in C/C++ In the switch statement we pass some value, and using different cases, we can check the value. Here we will see that we can use ranges in the case statement. After writing case, we have to put lower value, then one space, then three dots, then another space, and the higher value.
The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX. RAND_MAX is a constant whose default value may vary between implementations but it is granted to be at least 32767.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With