title: 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? (clamp)
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>Here's what I mean:</p>
  
  <pre><code>int limit(int lowerBound, int upperBound, int number)
  {
     return (number &lt; lowerBound) ? lowerBound : (number &gt; upperBound) ? upperBound : number;
  }
  
  int limit2(int lowerBound, int upperBound, int number)
  {
     if (number &lt; lowerBound)
     {
        return lowerBound;
     }
     else if (number &gt; upperBound)
     {
        return upperBound;
     }
     else
     {
        return number;
     }
  }
  </code></pre>
  
  <p><strong>[EDIT]</strong></p>
  
  <p>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).</p>
  
  <pre><code>int foo = Math.Max(Math.Min(upperBound, number), lowerBound);
  </code></pre>