O'Reilly logo

Professional .NET 2.0 Generics by Tod Golding

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required