Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I override ToString() method for all IEnumerable<Int32>?

I want to override ToString() on IEnumerable<Int32>.

I was thinking to use Extension methods.

But when I do this below, it still calls the ToString() on System.Object. When I rename my method, then it calls my method.

As my extension method is in a static class, I am not able to override.

How can I achieve this so that my ToString() implementation is called when I call .ToString() on List<Int32> for example?

public static class ExtensionMethods
{
    public static new string ToString(this IEnumerable<Int32> set)
    {
        var sb = new StringBuilder();

        // Do some modifications on sb

        return sb.ToString();
    }
}
like image 709
pencilCake Avatar asked Dec 12 '22 04:12

pencilCake


2 Answers

How can I achieve this so that my ToString() implementation is called when I call .ToString() on List for example?

You can't, basically. Extension methods are only used if no matching instance method can be found.

I suggest you give your method a different name, avoiding the problem - and the potential confusion your method would cause.

Note that even if extension methods were matched in preference to (say) methods declared on object, it would only make a difference for your own code being compiled with an appropriate using directive - not any other code which has already bound the call to the normal one.

If you can give more information about what you're trying to achieve, we may be able to help you more - but for the moment, something like ToDelimitedString (or whatever your method does) sounds like the best bet to me.

like image 197
Jon Skeet Avatar answered Dec 14 '22 18:12

Jon Skeet


You cannot replace a method using extension methods.

Method resolution will check for a method belonging to the type, before trying to find matching extension methods.

In other words, you cannot replace ToString, but yes, you can create your own method.

Either create your own IEnumerable<T> type with an overridden ToString method, or use a different method name. Of course, using your own type will of course only work when you're actually using that type.

like image 34
Lasse V. Karlsen Avatar answered Dec 14 '22 18:12

Lasse V. Karlsen