Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

A Generic Clamp Function for C#

0.00/5 (No votes)
31 Jan 2008 2  
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 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here