Update 1
I realised that the original restriction of a simple generic type meant that I was unable to compare objects of different kinds, regardless of whether they implemented IComparable<T> or not, as a result the latest is now:
public static bool IsLessThan<TSource, TComparer>(this TSource source, TComparer comparer)
where TSource : IComparable<TComparer>
where TComparer : IComparable<TComparer>
{
return source.CompareTo(comparer) < 0;
}
Original
I’ve written a simple IsLessThan(IComparable comparer) extension method on IComparable interface. I’ve ran into a small problem however; I’ve realised that essentially it allows for any IComparable to be compared, which I’d rather not have. Alternatively I’m wondering if it’s possible to restrict the parameter using a generic type? Currently my extension method looks like this:
public static bool IsLessThan(this IComparable source, IComparable comparer)
{
return source.CompareTo(comparer) < 0;
}
Is there any way to use generics to ensure that source and comparer are the same type, whilst still maintaining the constraint of IComparable?
Example
int test = 2;
var resultOne = test.IsLessThan(3); // should return true
var resultTwo = test.IsLessThan("Hello world"); // shouldn't compile
Well, you could use:
Or you could make it more constrained, using
IComparable<T>:The latter would also be more efficient in terms of avoiding boxing.