How to create an extension method for ToString?

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.


It sounds like you want to replace what files.ToString() returns. You will not be able to do that without writing a custom class to assign files as (i.e. inherit from List and override ToString().)

First, get rid of the generic type (<T>), you're not using it. Next, you will need to rename the extension method because calling files.ToString()will just call the List's ToString method.

This does what you're looking for.

static class Program
{
    static void Main()
    {
        var list = new List<string> { {"a"}, {"b"}, {"c"} };
        string str = list.ToStringExtended();
    }
}


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

Tags:

C#

.Net

Tostring