subclassing generics

Published 03-20-2007 5:39 PM | jokiz

I saw my teammate months ago using a hashtable in creating a lookup type of business objects.  Since we have just started using .NET 2.0, i told him about the new feature that comes with it that can be useful in his current task, generics.  I told him about the typesafe List of T and Dictionary of T which are the ones frequently used.

I was surprised later that when i was reading his code that generics was all over the place, it's kind of messy to read.  Methods were passing around List<BusinessObject> here and there, etc.  Not to mention the pain when you decided later that a collection/list of business objects should really be a dictionary type and you have to change the signatures of the involved methods.

Having said that, I prefer to introduce another class for the list type of business objects eventhough i don't have any added implementations List<T>.  Just like the .NET 1.x way where i have the CollectionBase inheritors.  That way, it would be easy for me if ever i needed to provide additional methods for it, , change it from a list type to a dictionary type, or even to read code (the last one is obviously relative).

Filed under:

Comments

# cruizer said on March 20, 2007 1:59 AM:

yeah, thanks to Keith Rull for telling me about it (via his blog) too -- :)

# keithrull said on March 20, 2007 9:53 AM:

Thanks for the props cruizer :)

Generics is great. Use if right and you'll have clean and maintanable code. Use it wrong and you'll be doomed with the curse of non-maintainability.

# Jon Limjap said on March 21, 2007 1:26 AM:

Yep, generics are great. Not only can you subclass them the way keithrull did, but you can add constraints so that your subclass only accepts objects of a specific type.

Great for the application above.

# jokiz said on March 21, 2007 11:28 PM:

@jon - you can also add the same constraint with collectionbase in .net 1.x, through onvalidate, but there is a trivial hack for that

# Keith Rull said on March 26, 2007 4:44 PM:

A few days ago we helped Rolvin sort the list of girls he wants to date .. this time we'll help him find