![]() |
Languages »
C# »
Generics
Beginner
License: The Code Project Open License (CPOL)
A Generic Clamp Function for C#By Mike McCabeA function for 'clamping' values to within a given range |
C# (C# 2.0, C# 3.0), Dev
|
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||
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;
}
int i = Clamp(12, 10, 0); -> i == 10
double d = Clamp(4.5, 10.0, 0.0); -> d == 4.5
| You must Sign In to use this message board. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 31 Jan 2008 Editor: Deeksha Shenoy |
Copyright 2008 by Mike McCabe Everything else Copyright © CodeProject, 1999-2009 Web22 | Advertise on the Code Project |