C# Clamp()
Published Nov 19, 2025
Contribute to Docs
The Math.Clamp() is a static method that returns the value clamped to the inclusive range of min and max.
Note: The static method
Math.Clamp()was introduced in .NET Core 2.0.
Syntax
Math.Clamp(value, min, max);
Parameters:
value: The value to be clamped.min: The lower bound of the result.max: The upper bound of the result.
Return value:
Returns the value clamped to the inclusive range of min and max.
Note: If value is less than
min, it returnsmin; if greater thanmax, it returnsmax; otherwise, it returnsvalue.
Example
The following example demonstrates the Math.Clamp() method and writes the result to the console.
using System;class Program{static void Main(){int min = 2;int max = 8;int result = Math.Clamp(10, min, max);Console.WriteLine(result);}}
The example will result in the following output:
8
Codebyte Example
In this example, a random list of decimal numbers is generated, and Math.Clamp() ensures that all stored values stay within the defined range:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C# on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn Microsoft's popular C# programming language, used to make websites, mobile apps, video games, VR, and more.
- Beginner Friendly.15 hours