Click here to Skip to main content
Licence CPOL
First Posted 30 Jan 2008
Views 30,293
Bookmarked 8 times

A Generic Clamp Function for C#

By Mike McCabe | 31 Jan 2008
A function for 'clamping' values to within a given range
1 vote, 11.1%
1
2 votes, 22.2%
2
2 votes, 22.2%
3
2 votes, 22.2%
4
2 votes, 22.2%
5
3.17/5 - 9 votes
μ 3.17, σa 2.44 [?]

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, 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

Member


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralI like more this one PinmemberAlberto Bencivenni1:31 6 Feb '08  
GeneralExcellence milk for babes PinmemberJadeZhao2:47 2 Feb '08  
GeneralGreat! PinmemberJean-Paul Mikkers10:34 1 Feb '08  
GeneralUsage examples PinmvpJ4amieC3:24 1 Feb '08  
GeneralRe: Usage examples PinmemberStockportJambo5:36 1 Feb '08  
GeneralRe: Usage examples PinmvpJ4amieC1:10 2 Feb '08  
GeneralSome comments. PinmemberEnnis Ray Lynch, Jr.18:03 31 Jan '08  
AnswerRe: Some comments. Pinmembermikemccabe0:06 1 Feb '08  
QuestionUsage? PinmemberPCoffey4:00 31 Jan '08  
AnswerRe: Usage? Pinmembermikemccabe12:58 31 Jan '08  
GeneralRe: Usage? PinmemberMladen Jankovic13:55 31 Jan '08  
GeneralRe: Usage? PinmemberPCoffey4:32 1 Feb '08  

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.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120209.1 | Last Updated 1 Feb 2008
Article Copyright 2008 by Mike McCabe
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid