5.1. The Basics

To illustrate the fundamental value of generic methods, let's start with the simplest of examples. Suppose you have a Max() function that accepts two double values, compares them, and returns the greater of the two values. This function might appear as follows:

[VB code]
Public Function Max(ByVal val1 As Double, ByVal val2 As Double) As Double
    Return IIf(val2 < val1, val1, val2)
End Function
[C# code]
public double Max(double val1, double val2) {
    return (val2 < val1) ? val1 : val2;
}

This method is handy for number-crunching applications. However, once you decide you want to apply this same Max() function to additional data types, you have a problem. This method can only be applied to double data types. You only have a few real, type-safe options that you can use to resolve this problem. One approach would be to create specific versions of this method to support each data type. However, doing that would force you to bloat your namespace with MaxString, MaxInt, and MaxLong methods. Not good. To get around the bloat issue, you might consider going back to using an object-based interface and tossing all type safety to the wind. Your last option here would be to provide several overloaded versions of Max() that accepted different types. That might represent some measure of improvement, but it's still not ideal.

This discussion of taking on bloat or compromising type safety is probably starting to sound like a broken record at this point. You see the same patterns over ...

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.