65.9K
CodeProject is changing. Read more.
Home

A Generic Clamp Function for C#

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.17/5 (9 votes)

Jan 31, 2008

CPOL
viewsIcon

74278

A function for 'clamping' values to within a given range

Introduction

This is my first C# generic function.

In computer terms, to clamp a value is to make sure that it lies between some maximum and minimum values. If it’s greater than the max value, then it’s replaced by the max, etc.

I first learned it in the context of computer graphics, for colors - it’s used, for instance, to make sure that your raytraced pixel isn't "blacker than black".

So:

    public static T Clamp<T>(T value, T max, T min)
         where T : System.IComparable<T> {     
        T result = value;
        if (value.CompareTo(max) > 0)
            result = max;
        if (value.CompareTo(min) < 0)
            result = min;
        return result;
    } 

Usage

    int i = Clamp(12, 10, 0); -> i == 10
    double d = Clamp(4.5, 10.0, 0.0); -> d == 4.5