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;
double d = 5.5;
Console.WriteLine("{0:0.00}", d.ConstrainToRange(1.0, 5.0));


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


Double click on the code to select all.