For the first method, the types of the two parameters have to be same, e.g., int
and int
. The type has to implement the IComparable
interface.
For the second method, the two parameters can have different types. Both types must implement the IComparable
interface, but do not have to be the same, e.g., int
and string
.
Note that the IComparable.CompareTo method will likely throw an exception if the types are not the same. So it's better to make sure that the types are actually the same. You can do this by using your first method, or even better by using the generic IComparable<T> interface.
The follow-up question is, of course: What is the difference between these two methods?
first:
public static int Foo<T1, T2>(T1 first, T2 second) where T1 : IComparable<T2>
{
return first.CompareTo(second);
}
second:
public static int Foo<T>(IComparable<T> first, T second)
{
return first.CompareTo(second)
}
Answer: The first method doesn't box the first argument, while the second method does.