What is Math.Clamp() in C#?

C# has a built-in Math class that provides useful mathematical functions and operations. The class has the Clamp() function, which is used to return a value clamped to an inclusive range of two specified numbers.

Syntax

This function returns the value clamped to the inclusive range of min_param and max_param.

Clamp (type value, type min_param, type max_param);

where:

  • value: is the value to be clamped
  • min_param: is the lower bound of result
  • max_param: is the upper bound of result

Return value

  • value: Returns this if min_param ≤ value ≤ max_param

    or

  • min_param: Returns this if value < min_param

    or

  • max_param: Returns this if value > max_param

Variants

Clamp(Single, Single, Single)

  public static float Clamp (float  value, float min_param, float max_param);

Clamp(Double, Double, Double)

  public static double Clamp (double  value, double min_param, double max_param);

Clamp(Decimal, Decimal, Decimal)

  public static decimal Clamp (decimal  value, decimal min_param, decimal max_param);

Clamp(Byte, Byte, Byte)

  public static byte Clamp (byte  value, byte min_param, byte max_param);

Clamp(Uint16, UInt16, UInt16)

  public static ushort Clamp (ushort  value, ushort min_param, ushort max_param);

Clamp(Uint32, UInt32, UInt32)

  public static uint Clamp (uint  value, uint min_param, uint max_param);

Clamp(Uint64, UInt64, UInt64)

  public static ulong Clamp (ulong  value, ulong min_param, ulong max_param);

Clamp(Sbyte, SByte, SByte)

  public static sbyte Clamp (sbyte  value, sbyte min_param, sbyte max_param);

Clamp(Int16, Int16, Int16)

  public static short Clamp (short  value, short min_param, short max_param);

Clamp(Int32, Int32, Int32)

  public static int Clamp (int  value, int min_param, int max_param);

Clamp(Int64, Int64, Int64)

  public static long Clamp (long value, long min_param, long max_param);

Example

using System;
class HelloWorld
{
static void Main()
{
System.Console.WriteLine(Math.Clamp(5,0,4));
System.Console.WriteLine(Math.Clamp(1,4,6));
System.Console.WriteLine(Math.Clamp(5,0,6));
}
}

Free Resources