Click here to Skip to main content
6,822,123 members and growing! (16,976 online)
Email Password   helpLost your password?
Languages » C# » Generics     Beginner License: The Code Project Open License (CPOL)

A Generic Clamp Function for C#

By Mike McCabe

A function for 'clamping' values to within a given range
C# (C#2.0, C#3.0), Dev
Posted:30 Jan 2008
Updated:31 Jan 2008
Views:15,882
Bookmarked:6 times
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
9 votes for this article.
Popularity: 3.02 Rating: 3.17 out of 5
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

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


Member

Location: United States United States

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 12 of 12 (Total in Forum: 12) (Refresh)FirstPrevNext
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  
GeneralUsage? PinmemberPCoffey4:00 31 Jan '08  
GeneralRe: 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    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

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

PermaLink | Privacy | Terms of Use
Last Updated: 31 Jan 2008
Editor: Deeksha Shenoy
Copyright 2008 by Mike McCabe
Everything else Copyright © CodeProject, 1999-2010
Web19 | Advertise on the Code Project