Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; } 
like image 411
Arseni Mourzenko Avatar asked Jul 04 '10 23:07

Arseni Mourzenko


People also ask

Is there Range function in C?

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.

What is the range of rand () in C?

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.


1 Answers

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; } 
like image 61
Trap Avatar answered Sep 28 '22 10:09

Trap