6

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);
}
dtb
  • 213,145
  • 36
  • 401
  • 431
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
  • 1
    it is not exact duplicate of that post, because here we have two parameter and it change some criteria. look at the first answer to see the difference – Hossein Narimani Rad Jan 21 '13 at 18:30

2 Answers2

13

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.

dtb
  • 213,145
  • 36
  • 401
  • 431
1

From the code fragment provided the difference that can say, that

Generics version:

  • for generics new code will be generated for every type defined

Foo<Class1>, Foo<Class2>, Foo<Class3>.

  • you need to define a type at compile time

Interface version:

  • benefit from OOP concepts, hiding implementation details from the actual code.

  • runtime type definiton (more flexibility), but less "generic" in terms of pure sence of that word.

In general: interface version is more flexible but less generic (everything, by the way, depends naturally on concrete code implementaiton).

Tigran
  • 61,654
  • 8
  • 86
  • 123