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

Limit<>

Limits a value to a maximum. For example this is usefull if you want to feed a progressBar with values from a source which eventually might exceed an expected maximum. This is a generic extension method with IComparable<T> constraint. So every type which implements the IComparable interface benefits from this extension.

Source

public static T Limit<T>(this T value, T maximum) where T : IComparable<T>
{
   return value.CompareTo(maximum) < 1 ? value : maximum;
}

Example

int testValue = 150;
int limitedResult = testValue.Limit(100);
// limitedResult will be 100 because it's the given maximum.

Author: Rainer Hilmer

Submitted on: 11 mei 2008

Language: C#

Type: System.IComparable<T>

Views: 6007