Click here to Skip to main content
15,884,979 members
Articles / Programming Languages / C#
Article

A Generic Clamp Function for C#

Rate me:
Please Sign up or sign in to vote.
3.17/5 (9 votes)
31 Jan 2008CPOL 72.8K   8   14
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:

C#
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

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

License

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


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionFailed clamp Pin
ShaneYu13-Jul-13 20:52
ShaneYu13-Jul-13 20:52 
Nice method but it doesn't appear to work completely...

int i = Clamp(-10, 3, 1);

'i' should result in 1, however the actual result is '-1'.

Are you able to improve upon this current generic method to fix this issue?
Regards,
Shane Yu

AnswerRe: Failed clamp Pin
ShaneYu13-Jul-13 21:02
ShaneYu13-Jul-13 21:02 
GeneralI like more this one Pin
Alberto Bencivenni6-Feb-08 0:31
Alberto Bencivenni6-Feb-08 0:31 
GeneralExcellence milk for babes Pin
Jadder Zhao2-Feb-08 1:47
Jadder Zhao2-Feb-08 1:47 
GeneralGreat! Pin
jpmik1-Feb-08 9:34
jpmik1-Feb-08 9:34 
GeneralUsage examples Pin
J4amieC1-Feb-08 2:24
J4amieC1-Feb-08 2:24 
GeneralRe: Usage examples Pin
StockportJambo1-Feb-08 4:36
StockportJambo1-Feb-08 4:36 
GeneralRe: Usage examples Pin
J4amieC2-Feb-08 0:10
J4amieC2-Feb-08 0:10 
GeneralSome comments. Pin
Ennis Ray Lynch, Jr.31-Jan-08 17:03
Ennis Ray Lynch, Jr.31-Jan-08 17:03 
AnswerRe: Some comments. Pin
Mike McCabe31-Jan-08 23:06
Mike McCabe31-Jan-08 23:06 
QuestionUsage? Pin
PCoffey31-Jan-08 3:00
PCoffey31-Jan-08 3:00 
AnswerRe: Usage? Pin
Mike McCabe31-Jan-08 11:58
Mike McCabe31-Jan-08 11:58 
GeneralRe: Usage? Pin
Mladen Janković31-Jan-08 12:55
Mladen Janković31-Jan-08 12:55 
GeneralRe: Usage? Pin
PCoffey1-Feb-08 3:32
PCoffey1-Feb-08 3:32 

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

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