What is the difference between these two methods?
first:
public static int Foo<T>(T first, T second) where T:IComparable
{
return first.CompareTo(second)
}
second:
public static int Foo(IComparable first, IComparable second)
{
return first.CompareTo(second);
}
For the first method, the types of the two parameters have to be same, e.g.,
intandint. The type has to implement theIComparableinterface.For the second method, the two parameters can have different types. Both types must implement the
IComparableinterface, but do not have to be the same, e.g.,intandstring.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:
second:
Answer: The first method doesn’t box the first argument, while the second method does.