C# Tutorial C# Advanced C# References

C# Math - Clamp() Method



The C# Clamp() method returns the value clamped to the inclusive range of min and max. The method returns the following:

  • If minvaluemax, the method returns value.
  • If value < min, the method returns min.
  • If value > max, the method returns max.

Syntax

public static ulong Clamp (ulong value, ulong min, ulong max);
public static uint Clamp (uint value, uint min, uint max);
public static ushort Clamp (ushort value, ushort min, ushort max);
public static float Clamp (float value, float min, float max);
public static sbyte Clamp (sbyte value, sbyte min, sbyte max);
public static long Clamp (long value, long min, long max);
public static int Clamp (int value, int min, int max);
public static short Clamp (short value, short min, short max);
public static double Clamp (double value, double min, double max);
public static decimal Clamp (decimal value, decimal min, decimal max);
public static byte Clamp (byte value, byte min, byte max);

Parameters

value Specify the value to be clamped.
min Specify the lower bound of the result.
max Specify the upper bound of the result.

Return Value

Returns the value clamped to the inclusive range of min and max.

Example:

In the example below, Clamp() method returns the value clamped to the inclusive range of min and max.

using System;

class MyProgram {
  static void Main(string[] args) {
    Console.WriteLine("Math.Clamp(25, 50, 100): "+
                       Math.Clamp(25, 50, 100));   
    Console.WriteLine("Math.Clamp(25, 0, 50): "+
                       Math.Clamp(25, 0, 50));      
    Console.WriteLine("Math.Clamp(25, -25, 0): "+
                       Math.Clamp(25, -25, 0));  
  }
}

The output of the above code will be:

Math.Clamp(25, 50, 100): 50
Math.Clamp(25, 0, 50): 25
Math.Clamp(25, -25, 0): 0

❮ C# Math Methods