Rob Garrett - Blogs

Welcome to Rob Garrett - Blogs Sign in | Join | Help
in Search
Google

Software/Technology Discussion

Software and Technology Tid-bits

Question about generics

In my previous post on Generics, I received a comment from Eddie, who was asking why developers would want to use the following constraint, in the example below, when he would pass the parameters as IComparable interface types.


The previous comment touches on the generics vs base class debate, of which there is pros and cons to both.

Eddie raises an interesting question, and I am giving it some thought. A few reasons for not using IComparable as the parameter type come to mind...

If you wanted to compare value types, casting to IComparable would convert the value types to a references by boxing, which is what generics are trying to avoid.

A reference is 4 bytes in length, so, when comparing two short values,  Eddie's example would pass at least 8 bytes across the stack (+ overhead). Using a generic with Unit16 type would only use of 4 bytes for the two parameters.   

Eddie's example would require up casting the interface reference type to known type if the method did more than just compare two values with CompareTo. The whole point of generics is that the developer of a generic should not have to know anything about the intended type used in the generic context. Otherwise, we might as well use cast from System.Object like ArrayList does.
Share this post: Email it! | bookmark it! | digg it! | reddit!
Published Thursday, May 26, 2005 11:32 PM by Rob Garrett

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
(optional)
(required) 
Submit

Blurb


Head Shot
Rob Garrett is a British Expat living in Maryland USA. Rob is a trained software engineer and experienced in Windows .NET development.

Rob enjoys listening to Rock music, posting to blogs, driving in the country with the sunroof open, beer (not in conjunction with country driving) and spending time with his family.

This Blog

Syndication

Powered by Community Server, by Telligent Systems