|
| 1 | +--- |
| 2 | +Title: 'Clamp()' |
| 3 | +Description: 'Restricts a value to lie within a specified minimum and maximum range.' |
| 4 | +Subjects: |
| 5 | + - 'Code Foundations' |
| 6 | + - 'Computer Science' |
| 7 | +Tags: |
| 8 | + - 'Arithmetic' |
| 9 | + - 'Method' |
| 10 | + - 'Numbers' |
| 11 | +CatalogContent: |
| 12 | + - 'learn-c-sharp' |
| 13 | + - 'paths/computer-science' |
| 14 | +--- |
| 15 | + |
| 16 | +The **`Math.Clamp()`** is a static method that returns the value clamped to the inclusive range of min and max. |
| 17 | + |
| 18 | +> **Note:** The static method `Math.Clamp()` was introduced in .NET Core 2.0. |
| 19 | +
|
| 20 | +## Syntax |
| 21 | + |
| 22 | +```pseudo |
| 23 | +Math.Clamp(value, min, max); |
| 24 | +``` |
| 25 | + |
| 26 | +**Parameters:** |
| 27 | + |
| 28 | +- `value`: The value to be clamped. |
| 29 | +- `min`: The lower bound of the result. |
| 30 | +- `max`: The upper bound of the result. |
| 31 | + |
| 32 | +**Return value:** |
| 33 | + |
| 34 | +Returns the value clamped to the inclusive range of min and max. |
| 35 | + |
| 36 | +> **Note:** If value is less than `min`, it returns `min`; if greater than `max`, it returns `max`; otherwise, it returns `value`. |
| 37 | +
|
| 38 | +## Example |
| 39 | + |
| 40 | +The following example demonstrates the `Math.Clamp()` method and writes the result to the console. |
| 41 | + |
| 42 | +```cs |
| 43 | +using System; |
| 44 | + |
| 45 | +class Program |
| 46 | +{ |
| 47 | + static void Main() |
| 48 | + { |
| 49 | + int min = 2; |
| 50 | + int max = 8; |
| 51 | + |
| 52 | + int result = Math.Clamp(10, min, max); |
| 53 | + Console.WriteLine(result); |
| 54 | + } |
| 55 | +} |
| 56 | +``` |
| 57 | + |
| 58 | +The example will result in the following output: |
| 59 | + |
| 60 | +```shell |
| 61 | +8 |
| 62 | +``` |
| 63 | + |
| 64 | +## Codebyte Example |
| 65 | + |
| 66 | +In this example, a random list of decimal numbers is generated, and `Math.Clamp()` ensures that all stored values stay within the defined range: |
| 67 | + |
| 68 | +```codebyte/csharp |
| 69 | +using System; |
| 70 | +
|
| 71 | +class Example |
| 72 | +{ |
| 73 | + static void Main() |
| 74 | + { |
| 75 | + Random random = new Random(); |
| 76 | + double[] nums = new double[10]; |
| 77 | + int min = 1; |
| 78 | + int max = 50; |
| 79 | +
|
| 80 | + for (int i = 0; i < nums.Length; i++) |
| 81 | + { |
| 82 | + double range = random.NextDouble() * 70 - 10; // -10 to 60 |
| 83 | + double limit = Math.Clamp(range, min, max); |
| 84 | + nums[i] = limit; |
| 85 | + } |
| 86 | +
|
| 87 | + foreach (double num in nums) |
| 88 | + { |
| 89 | + Console.WriteLine(num); |
| 90 | + } |
| 91 | + } |
| 92 | +} |
| 93 | +``` |
0 commit comments