C# Clamp()

stuartmosquera's avatar
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.

  • 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

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 returns min; if greater than max, it returns max; otherwise, it returns value.

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:

Code
Output
Loading...

All contributors

Contribute to 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