5.5. Overloading Generic Methods

When working with generic methods, it's important to understand how the introduction of type parameters impacts the uniqueness of your method's signature. This is especially significant if you're creating overloaded versions of your method. Fortunately, for the most part, generic methods conform to the same rules as non-generic methods. The addition of type parameters, however, does create a few new wrinkles that are worth considering.

The following examples of generic method declarations illustrate how the compiler will go about evaluating your methods. This first set of declarations looks at uniqueness for a mix of generic and non-generic methods:

[VB code]
Public Sub Foo(ByVal myStrParam As String)
End Sub

Public Sub Foo(Of I)(ByVal myStrParam As String)
End Sub
[C# code]
public void Foo(string myStrParam) {}

public void Foo<I>(string myStrParam) {}

The two methods declared here share much in common. They both have the same name, Foo, and they have identical parameter signatures. Well, kind of. The second declaration is a generic method that introduces an additional parameter, a type parameter. This additional parameter, as you might suspect, becomes part of the method's overall signature and creates a point of distinction that allows the compiler to treat each of these method declarations as being unique.

The return type of a method can also never be used as a distinguishing characteristic of your method's interface. This rule, which applies ...

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.