1

Take a look at the following code

namespace OverLoadTest
{
    class Program
    {
        static void Main(string[] args)
        {
            ulong value = 10;

            var foo = new Foo();
            foo.DoStuff(value);
        }
    }


    public class Foo
    {
        public void DoStuff(float value)
        {
            // This is the resolved overload even if we have an extension method that takes ulong
        }
    }

    public static class FooExtensions
    {
        public static void DoStuff(this Foo foo, ulong value)
        {

        }
    }
}

Can someone explain why the extension method taking an ulong is not invoked here?

seesharper
  • 3,249
  • 1
  • 19
  • 23
  • @RufusL because its an extension of `Foo` thats takes a `ulong`, not an extension of `ulong` – TheBatman Feb 19 '20 at 20:43
  • 4
    Have a look at [specs](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods#binding-extension-methods-at-compile-time) _An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself._ – Pavel Anikhouski Feb 19 '20 at 20:43
  • Also see [this answer](https://stackoverflow.com/a/2118122/47589), which is probably a better duplicate than the first, and supports Pavel's comment. –  Feb 19 '20 at 20:43
  • If an implicit conversion can avoid using an extension method then it gets favored. An implicit conversion from ulong to float can't make many programmers happy, but that's the way it rolls. – Hans Passant Feb 19 '20 at 20:44

0 Answers0