11.7. Support for Polymorphic Recursion

Another upside of the .NET generics implementation is its support for polymorphic recursion. Through polymorphic recursion, you are allowed to call generic methods recursively, supplying alternate type parameters for each recursive call. Here's an example that illustrates this concept in action:

[VB code]
Public Class RecursionClass
    Public count As Int32 = 0
    Public Sub Foo(Of T)(ByVal val As T)
        If (count <= 1) Then
            count = count + 1
            Console.Out.WriteLine("Type = {0}", val.GetType())
            Me.Foo(Of String)("String Param")
        End If
    End Sub

    Public Sub DumpTypes()
        Me.Foo(Of Int32)(123)
    End Sub
End Class
[C# code]
public class RecursionClass {
    public int count = 0;
    public void Foo<T>(T val) {
        if (count <= 1) {
            count++;
            Console.Out.WriteLine("Type = {0}", val.GetType());
            this.Foo<String>("String Param");
        }
    }

    public void DumpTypes() {
        this.Foo<int>(123);
    }
}

This class includes a generic Foo() method that simply displays the type name of the supplied type parameter before recursively calling itself again with a string type argument. You'll notice that this method is invoked by the DumpTypes() method, which actually supplies an integer type argument. The key point here is that the Foo() method was able to call itself recursively with a type argument that had a type that was different from the type that was initially received. This ability to achieve recursion with varying types of arguments is quite powerful and an important byproduct of the .NET generic ...

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.