1

I've done a fair bit of reading and there are plenty of answers to very similar questions but even following those I can't get this to work. The extension method is static, public, has this, is in the same namespace so should not need importing... what am I missing? My C# isn't great.

namespace LDB
{

    public enum Neg { isNegated, notNegated };

    static class NegStringifier {
        public static string ToString(this Neg n) {
            string res = n switch {
                Neg.isNegated => "flowers",
                Neg.notNegated => "kittens",
                //_ => null
            };
            return res;
        }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            System.Console.WriteLine(Neg.isNegated.ToString());
            System.Console.WriteLine(Neg.notNegated.ToString());
            ...

output:

isNegated
notNegated

Apologies up front, I know this is going to be something trivial but I can't see what.

user3779002
  • 566
  • 4
  • 17

1 Answers1

5

The compiler only looks for extension methods when it can't find any "regular" instance methods that are applicable for the method call. In this case, the object class provides a ToString() method, so there is an appropriate method there, and that's what the compiler uses.

If you change ToString to some other name (e.g. ExtensionToString) in both the extension method and calling code, you'll see it being used.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • So my method is being hidden. Would it not be a thing for the compiler to report this as unreachable? – user3779002 Oct 20 '20 at 15:31
  • 4
    @user3779002: No, it's not being hidden - it's not being looked for. And it's not unreachable - you could call `NegStringifier.ToString(Neg.isNegated)` for example. – Jon Skeet Oct 20 '20 at 15:33