2.2. Least Common Denominator Programming

In the early days of Java, I remember discussing templates with a few of the C++ converts. Whenever the conversation turned to templates (the C++ variation of generics), they usually said: "I don't need templates because everything in Java descends from an object." And, I'm assuming this same train of thought has actually carried forward into some segment of the .NET community, where every class is also rooted in a common object type.

This general mindset has always puzzled me. I understand that having everything rooted in a single object hierarchy enables some generality. It even makes sense to me that a number of classes would leverage this reality. At the same time, I don't think it would be accurate to view this feature as somehow replacing or offsetting the need for generics.

The Object data type, in fact, can end up being quite a crutch. Developers will leverage it in a number of situations where they want to provide a highly generalized interface that accepts any number of different data types. ArrayList is the great example of a class that takes this approach. As a data container, it needs to be able to hold any type of object. So, it's forced to use the Object data type to represent the types it holds. You'll also see situations where developers will accept or return Object parameters in an interface that needs to handle a wide variety of unrelated objects.

This use of the Object type is natural and expected. If ArrayList and ...

Get Professional .NET 2.0 Generics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.