How to create an extension method for ToString?

IAdapter picture IAdapter · Feb 13, 2011 · Viewed 27.1k times · Source

I have tried this:

public static class ListHelper
{
    public static string ToString<T>(this IList<String> list)
    {
        return string.Join(", ", list.ToArray());
    }

    public static string ToString<T>(this String[] array)
    {
        return string.Join(", ", array);
    }
}

But it does not work, both for string[] and List<string>. Maybe I need some special annotations?

Answer

Eric Lippert picture Eric Lippert · Feb 13, 2011

Extension methods are only checked if there are no applicable candidate methods that match. In the case of a call to ToString() there will always be an applicable candidate method, namely, the ToString() on object. The purpose of extension methods is to extend the set of methods available on a type, not to override existing methods; that's why they're called "extension methods". If you want to override an existing method then you'll have to make an overriding method.