Reputation: 10443
I wrote a generic extension method to see if a Key is in a certain range:
public static bool IsInRange(this Key key, Key lowerBoundKey, Key upperBoundKey )
{
return lowerBoundKey <= key && key <= upperBoundKey;
}
That seems simple enough, but suppose I want to write a generic method equivalent that will work with any type that can use the <=
comparison operator:
public static bool IsInRange(this T value, T lowerBound, T upperBound )
{
return lowerBound <= value && value <= upperBound;
}
How do I apply where T : ISomethingIDontKnow
so I can make this compile?
Upvotes: 1
Views: 42
Reputation: 247123
Converting the method to a generic method with where T : IComparable
should be enough for this to work.
public static bool IsInRange<T>(this T value, T lowerBound, T upperBound )
where T : IComparable {
return value != null && lowrBound != null && upperBound !=null
&& lowerBound.CompareTo(value) <= 0 && value.CompareTo(upperBound) <= 0;
}
Upvotes: 3