0

Perhaps this question sounds silly, but why does a generic and a non-generic IComparable interface exist?

Furthermore, which one is prefered to use and why?

John Threepwood
  • 15,593
  • 27
  • 93
  • 149

1 Answers1

5

The non-generic IComparable was added in version 1.1 before generics were introduced, while IComparer<T> was added alongside generics in version 2.0.

The generic version is preferred for the same reason as all generic interfaces - it is safer and documents the intent more clearly. Struct types also do not need to be boxed when passed to a generic method, as they would be for one with an object argument like IComparable.CompareTo so there is also a performance benefit.

Lee
  • 142,018
  • 20
  • 234
  • 287
  • Thank you. The non-generic version was not removed due to compatibility reasons, I guess? – John Threepwood Jun 20 '13 at 21:51
  • _And_ if it's used against a `struct` it will pass it without boxing it. – Chris Sinclair Jun 20 '13 at 21:51
  • @JohnThreepwood Right: there was no reason to actively *break* the developers who used the non-generic interface. They were free to upgrade at their leisure, of course. – dlev Jun 20 '13 at 21:52
  • @ChrisSinclair - I've updated the answer to include the boxing advantage. – Lee Jun 20 '13 at 21:55
  • @JohnThreepwood Removing all non-generic versions of classes would have meant that all pre-2.0 .NET code would have ceased to function. That's not something you want. As a side note: Java had the same issue and went a different path: Instead of having non-generic and generic classes, they turned generics into a compiler feature instead of a language feature: After compilation, all generic type information is gone, using normal non-generic classes. This is known as type erasure. I would call this the worst decision ever made by the Java guys, by the way. – Jan Dörrenhaus Jun 20 '13 at 21:59
  • @JanDoerrenhaus Oh I see, thank you for the background information. This is very interesting to me. I heard of the Java's type erasure in the context of Scala, where it is also a problem. Knowing the background, I see the reason to keep the non-generic versions. But at first glance, I was very confused, I must admit. – John Threepwood Jun 20 '13 at 22:02