Click here to Skip to main content
Click here to Skip to main content
Go to top

A Generic Clamp Function for C#

, 31 Jan 2008
Rate this:
Please Sign up or sign in to vote.
A function for 'clamping' values to within a given range


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".


    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;


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


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Mike McCabe

United States United States
No Biography provided

Comments and Discussions

QuestionFailed clamp PinmemberShaneYu13-Jul-13 20:52 
AnswerRe: Failed clamp PinmemberShaneYu13-Jul-13 21:02 
GeneralI like more this one PinmemberAlberto Bencivenni6-Feb-08 0:31 
GeneralExcellence milk for babes PinmemberJadeZhao2-Feb-08 1:47 
GeneralGreat! PinmemberJean-Paul Mikkers1-Feb-08 9:34 
GeneralUsage examples PinmvpJ4amieC1-Feb-08 2:24 
GeneralRe: Usage examples PinmemberStockportJambo1-Feb-08 4:36 
GeneralRe: Usage examples PinmvpJ4amieC2-Feb-08 0:10 
GeneralSome comments. PinmemberEnnis Ray Lynch, Jr.31-Jan-08 17:03 
AnswerRe: Some comments. Pinmembermikemccabe31-Jan-08 23:06 
QuestionUsage? PinmemberPCoffey31-Jan-08 3:00 
AnswerRe: Usage? Pinmembermikemccabe31-Jan-08 11:58 
GeneralRe: Usage? PinmemberMladen Jankovic31-Jan-08 12:55 
GeneralRe: Usage? PinmemberPCoffey1-Feb-08 3:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 1 Feb 2008
Article Copyright 2008 by Mike McCabe
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid