Saturday, July 12, 2008

Do we even need those non-generic interfaces?

Ever since generics was introduced in .NET 2.0, developers have been switching from the ArrayList to the List generic collection class. It makes life easier for the developers because they don't have to cast into the datatype that they need while retrieving. (Sure, there is the StringCollection class but what about when you don't have strings to deal with?)

Taking the use of generics to the next level, we then get developers into the idea of using the Generic interfaces - take IComparable as an example...

Normally, you would implement IComparable with a CompareTo(object) where you would cast the object into the type you are comparing with. With IComparable, you can compare against something you do not have to cast such as CompareTo(int) or CompareTo(CompensationPackage).

Theoretically, the idea seems to work pretty well but you would notice that a couple of the .NET framework classes just won't play along. Take the Array.Sort method, for instance - it will just complain about not finding an implementation of the non-generic IComparable. The same applies to the Array.Sort method which deceptively seems to indicate that it is a generic variant or Array.Sort.

...so yet again, we're stuck with having to implement non-generic interfaces till a 'truly generic' version of Array.Sort comes along.

(Coming up soon: Extension methods to get around this issue)

No comments: