ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

ConstrainToRange

Many times you may wish to impose boundaries on what a certain variable can be. This is especially useful for validating user input. For any comparable, it simply returns the value, truncated by a minimum or maximum

Source

public static T ConstrainToRange<T>(this T d, T min, T max) where T : IComparable
{
	if (d.CompareTo(min) < 0) return min;
	else if (d.CompareTo(max) > 0) return max;
	else return d;
}

Example

double d = 5.5;
Console.WriteLine("{0:0.00}", d.ConstrainToRange(1.0, 5.0));

Author: David Harris

Submitted on: 21 aug 2010

Language: C#

Type: System.IComparable<T>

Views: 4464