Generics give us a powerful reuse mechanism through composition. However, this can lead to some pretty complex type declarations. The compiler can infer generic types, but only for methods. To take advantage of this power a class, we need to wrap its constructor in a factory method.

A factory method is just a static method of a utility class that constructs an object. The factory method takes the same parameters as the constructor, and has the same type placeholders. The advantage of using the factory method over the constructor directly, however, is that the compiler can infer the types based on the method parameters.

In fact, when the factory method is used to create an object to immediately pass to another generic method, it can eliminate the type declaration altogether. This gives us extremely elegant code that doesn't appear to use generics at all.

Public Class ComparerHelper

    Public Shared Function Reverse(Of T) _
        (ByVal comparer As IComparer(Of T)) _
        As IComparer(Of T)

        Return New ReverseComparer(Of T) _
            (comparer)
    End Function

End Class

phoneBook.Sort( _
    ComparerHelper.Reverse( _
        New PhoneBookComparer))
public class ComparerHelper
{
    public static IComparer<T> Reverse<T>
        (IComparer<T> comparer)
    {
        return new ReverseComparer<T>
            (comparer);
    }
}



phoneBook.Sort(
    ComparerHelper.Reverse(
        new PhoneBookComparer()));